到目前为止,我已经完成的是应用程序重定向到同意页面。用户接受后,我会带着有效的授权码重定向回本地主机。据我所知,我需要进行另一个调用并交换此代码以获取访问令牌。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!!!
});
};
非常高兴我成功了!非常感谢大家