javascript - 使用 Node JS 对 Google API 进行身份验证
问题描述
到目前为止,我所拥有的是应用程序重定向到同意页面。用户接受,然后我将使用有效的授权代码重定向回 localhost。据我了解,我需要打另一个电话并将此代码交换为访问令牌。 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!!!
});
};
很高兴我得到了这个工作!非常感谢大家
解决方案
3-legged Google OAuth 虚拟指南。
从字面上看,您需要知道的一切都在这个单一页面https://developers.google.com/identity/protocols/OAuth2WebServer上。读两遍,您将成为 OAuth 忍者。总而言之,它说...
- 使用 4 个查询参数构造一个 accounts.google.com 网址:-
client_id
识别您的应用scope
说出您要求的权限redirect_uri
告诉谷歌将用户的浏览器重定向到哪里response_type=code
说你想要一个验证码
- 将用户的浏览器重定向到该 URL
- 在用户登录时喝一口咖啡,选择他的 Google 帐户并授予权限,直到最终......
- 用户的浏览器被重定向回您的应用程序
redirect_uri
,其中的查询参数code
是一次性 Auth Code - 将 Auth Code 发布到 Google 的令牌端点
- 解析 JSON 响应以获取访问令牌
- 在“authorization: Bearer access_token”http 标头中为您的后续 Google API 请求使用访问令牌
如果您访问https://developers.google.com/oauthplayground/,您可以在线运行这些步骤以查看各种 URL 和响应的样子。
推荐阅读
- azure - 在 Azure 流分析上获取正在运行的汽车之间的实时距离
- flutter - How to create user history page similar to 'my activity' on google - flutter
- macos - 请问如何在颤振桌面中使用谷歌地图?
- java - 如何使用 Spring Data Elasticsearch 使用 OR 逻辑创建对 Elasticsearch 的复杂查询?
- mysql - 如何计算百分比mysql窗口函数
- c# - PopToRootAsync 到选定的 Shell Flyout 项
- python - 使用 pysftp 在 .zip 中下载 CSV
- python - 汇总分类变量时超出最大递归深度
- python-3.x - 如何根据所需模板编辑 Pandas DataFrame?
- google-cloud-firestore - Firestore 规则:如何允许对其他人的记录进行特定编辑?