gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:10:39 24 4
gpt4 key购买 nike

到目前为止,我所拥有的是应用重定向到同意页面。用户接受,然后我将使用有效的授权代码重定向回 l​​ocalhost。据我了解,我需要打另一个电话并将此代码交换为访问 token 。但是,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 答案中的链接文章,并注意到了他的答案中列出的步骤。列出简单的步骤有助于我更清楚地理解。此外,按照评论中的建议,我删除了 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!!!
});
};

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

最佳答案

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 告诉 Google 将结果重定向到用户浏览器的位置
    4. response_type=code 表示您想要一个验证码
  2. 将用户的浏览器重定向到该 URL
  3. 在用户登录时喝杯咖啡,选择他的 Google 帐户并授予权限,直到最终...
  4. 用户的浏览器被重定向回您应用的 redirect_uri,查询参数为 code,即一次性验证码
  5. 将验证码发布到 Google 的 token 端点
  6. 解析 JSON 响应以获取访问 token
  7. 在“authorization: bearer access_token”http header 中为您的后续 Google API 请求使用访问 token

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

关于javascript - 使用 Node JS 对 Google API 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com