使用Node JS对Google API进行身份验证

Cra*_*ste 12 javascript google-api node.js google-oauth

到目前为止,我的应用程序重定向到同意页面.用户接受,然后我使用有效的授权码重定向回localhost.根据我的理解,我需要进行另一次调用并将此代码交换为访问令牌. getAccessToken()然而,不起作用.控制台日志返回:

invalid_client
invalid_request
Run Code Online (Sandbox Code Playgroud)

请告诉我需要哪些其他信息.

这是相关的代码:

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);
    });
};
Run Code Online (Sandbox Code Playgroud)

总结以及对我有用的东西

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

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!!!
    });
};
Run Code Online (Sandbox Code Playgroud)

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

pin*_*yid 12

Dummy的三脚Google OAuth指南.

您需要知道的所有内容都在此单页https://developers.google.com/identity/protocols/OAuth2WebServer上.阅读两次,你将成为OAuth忍者.总之,它说......

  1. 使用4个查询参数构建accounts.google.com网址: -
    1. client_id 识别您的应用程序
    2. scope 说出你要求的权限
    3. redirect_uri 告诉Google将结果重定向到用户浏览器的位置
    4. response_type=code 说你想要一个验证码
  2. 将用户的浏览器重定向到该URL
  3. 在用户登录时喝一口咖啡,选择他的Google帐户,并授予许可,直到最终......
  4. 用户的浏览器被重定向回您的应用程序redirect_uri,其查询参数code是一次性验证码
  5. 将验证码发布到Google的令牌端点
  6. 解析JSON响应以获取访问令牌
  7. 对于后续的Google API请求,请在"authorization:bearer access_token"http标头中使用访问令牌

如果您访问https://developers.google.com/oauthplayground/,则可以在线完成这些步骤,以查看各种网址和响应的外观.