首页 > 解决方案 > 使用 Node JS 对 Google API 进行身份验证

问题描述

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

invalid_client
invalid_request

请让我知道需要哪些附加信息。

以下是相关代码:

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它是因为它不那么冗长。我最终得到的代码如下所示:

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!!!
    });
};

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

标签: javascriptnode.jsgoogle-apigoogle-oauth

解决方案


3-legged Google OAuth 虚拟指南。

从字面上看,您需要知道的一切都在这个单一页面https://developers.google.com/identity/protocols/OAuth2WebServer上。读两遍,您将成为 OAuth 忍者。总而言之,它说...

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

如果您访问https://developers.google.com/oauthplayground/,您可以在线运行这些步骤以查看各种 URL 和响应的样子。


推荐阅读