使用 Node JS 向 Google API 进行身份验证 [英] Authenticate to Google API with Node JS

查看:23
本文介绍了使用 Node JS 向 Google API 进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止我所拥有的是应用程序重定向到同意页面.用户接受,然后我使用有效的授权代码重定向回本地主机.据我了解,我需要再打一次电话并用此代码交换访问令牌.但是,getAccessToken() 不起作用.控制台日志返回这个:

What I have so far is the app redirects to the consent page. The user accepts, then I'm redirected back to localhost with a valid authorization code. From what I understand, I need to make another call and exchange this code for an access token. getAccessToken() is not working, however. The console log is returning this:

invalid_client
invalid_request

请告诉我需要哪些附加信息.

Please let me know which additional information is needed.

相关代码如下:

var { google } = require('googleapis');
var http = require("http");
var request = require('request');

var oauth2Client = new google.auth.OAuth2(
    '<My Client ID>',
    '<My Client Secret>',
    'http://localhost:8080'
);

exports.generateAuthCodeUrl = function () {

    const url = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: 'https://www.googleapis.com/auth/blogger'
    });

    return url;
};


exports.getAccessToken = function (accessCode) {
    var codeOptions = {
        code: accessCode
    }
    oauth2Client.getToken(codeOptions, function (err, tokens) {
        // Now tokens contains an access_token and an optional refresh_token. Save them.
        if (!err) {
            oauth2Client.setCredentials(tokens);
            return tokens;
        }
        console.log(err.message);
    });
};

<小时>

总结以及对我有用的内容

我从 pinoyyid 的回答中阅读了 TWICE 中的链接文章,并记下了他的回答中列出的步骤.列出简单的步骤有助于我更清楚地理解.此外,正如评论中所建议的,我删除了 googleapi 库(上述错误发生在该库的代码中)并且只是对必要的端点进行了定期调用使用 request 库.我使用了 request 因为它不那么冗长.我最终得到的代码如下所示:


Summary and what worked for me

I read the linked article from pinoyyid's answer TWICE and also noted the steps listed in his answer. Listing the simple steps helped me understand more clearly. Also, as recommended in the comments, I removed the googleapi library (The error mentioned above was occurring within the code of this library) and just made regular calls to the necessary endpoints with the request library. I used request because it's much less verbose. The code that I ended up with looks like this:

exports.generateAuthCodeUrl = function () {

    var authURL = "https://accounts.google.com/o/oauth2/v2/auth?" +
        "client_id=" + client_id +
        "&scope=" + scope +
        "&redirect_uri=" + redirect_uri +
        "&response_type=" + response_type;

    //redirect to consent page
    return authURL;  
};

exports.getAccessToken = function (x) {
    var postDataUrl = 'https://www.googleapis.com/oauth2/v4/token?' +
        'code=' + x +  //auth code received from the previous call
        '&client_id=' + client_id +
        '&client_secret=' + client_secret +
        '&redirect_uri=' + redirect_uri +
        '&grant_type=' + "authorization_code"

    var options = {
        uri: postDataUrl,
        method: 'POST'
    };

    request(options, function (err, res, body) {
        return body; //returns an object with an access token!!!
    });
};

很高兴我得到了这个工作!非常感谢大家

Very glad I got this working!! Thank you all so much

推荐答案

The Dummy's Guide to 3-legged Google OAuth.

实际上您需要知道的一切都在这个页面上 https://developers.google.com/identity/protocols/OAuth2WebServer .阅读两遍,您将成为 OAuth 忍者.总之,它说...

Literally everything you need to know is on this single page https://developers.google.com/identity/protocols/OAuth2WebServer . Read it twice and you'll be an OAuth ninja. In summary, it says ...

  1. 使用 4 个查询参数构建一个 accounts.google.com URL:-
  1. Construct an accounts.google.com URL with 4 query params :-
  1. client_id 用于识别您的应用
  2. scope 说明您要求的权限
  3. redirect_uri 告诉 Google 将用户的浏览器重定向到哪里并带有结果
  4. response_type=code 表示你想要一个验证码
  1. client_id to identify your app
  2. scope to say what permissions you're asking for
  3. redirect_uri to tell Google where to redirect the user's browser with the result
  4. response_type=code to say you want an Auth Code

  • 将用户的浏览器重定向到该 URL
  • 在用户登录时喝一口咖啡,选择他的 Google 帐户并授予权限,直到最终...
  • 用户的浏览器被重定向回您应用的redirect_uri,查询参数为code,这是一次性的验证码
  • 将身份验证代码发布到 Google 的令牌端点
  • 解析 JSON 响应以获取访问令牌
  • 在随后的 Google API 请求的authorization:bearer access_token"http 标头中使用访问令牌
  • redirect the user's browser to that URL
  • Have a sip of coffee while the user logs in, chooses his Google account, and grants permission, until eventually ...
  • The user's browser gets redirected back to your app's redirect_uri, with a query param of code which is the one-time Auth Code
  • Post the Auth Code to Google's token endpoint
  • Parse the JSON response to get the Access Token
  • Use the Access Token in a "authorization: bearer access_token" http header for your subsequent Google API requests
  • 如果您转到 https://developers.google.com/oauthplayground/,您可以运行通过在线步骤查看各种 URL 和响应是什么样的.

    If you go to https://developers.google.com/oauthplayground/ you can run through the steps online to see what the various URLs and responses look like.

    这篇关于使用 Node JS 向 Google API 进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆