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

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

问题描述

到目前为止,我将应用程序重定向到同意页面.用户接受,然后使用有效的授权代码将我重定向回localhost.据我了解,我需要再次拨打电话并将此代码交换为访问令牌.但是,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

推荐答案

3腿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个查询参数构造一个account.google.com网址:-
  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响应以获取访问令牌
  • 在"authorization:bearer access_token" http标头中使用访问令牌,以用于后续的Google API请求
  • 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天全站免登陆