【发布时间】:2019-06-03 11:07:01
【问题描述】:
到目前为止,我所拥有的是应用重定向到同意页面。用户接受,然后我将使用有效的授权代码重定向回 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 答案中的链接文章,并注意到了他的答案中列出的步骤。列出简单的步骤有助于我更清楚地理解。此外,按照 cmets 中的建议,我删除了 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!!!
});
};
很高兴我得到了这个工作!非常感谢大家
【问题讨论】:
-
如果您可以使用 passport.js,请告诉我.. 我可以提供帮助
-
@programoholic 目前正在寻找纯节点答案。但如果我们走特快和护照路线,将来可能会更新。
-
我的2c,扔掉库,直接调用endpoints。这是获取身份验证代码的一个重定向,然后是一个简单的 REST 调用以将其交换为访问/刷新令牌。如果您有任何问题,可以将您的 http 请求与来自 Google OAuth 游乐场的请求进行比较,看看您遇到了什么问题。
-
@pinoyyid 这听起来确实是个好主意。我会尝试不使用图书馆。
-
如果有帮助,我已经发布了 Dummy's Guide to Oauth 作为设置步骤的答案。
标签: javascript node.js google-api google-oauth