Cra*_*ste 12 javascript google-api node.js google-oauth
到目前为止,我的应用程序重定向到同意页面.用户接受,然后我使用有效的授权码重定向回localhost.根据我的理解,我需要进行另一次调用并将此代码交换为访问令牌. getAccessToken()
然而,不起作用.控制台日志返回:
invalid_client
invalid_request
Run Code Online (Sandbox Code Playgroud)
请告诉我需要哪些其他信息.
这是相关的代码:
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);
});
};
Run Code Online (Sandbox Code Playgroud)
我从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!!!
});
};
Run Code Online (Sandbox Code Playgroud)
很高兴我得到了这个工作!非常感谢你们
pin*_*yid 12
Dummy的三脚Google OAuth指南.
您需要知道的所有内容都在此单页https://developers.google.com/identity/protocols/OAuth2WebServer上.阅读两次,你将成为OAuth忍者.总之,它说......
client_id
识别您的应用程序scope
说出你要求的权限redirect_uri
告诉Google将结果重定向到用户浏览器的位置response_type=code
说你想要一个验证码redirect_uri
,其查询参数code
是一次性验证码如果您访问https://developers.google.com/oauthplayground/,则可以在线完成这些步骤,以查看各种网址和响应的外观.
归档时间: |
|
查看次数: |
2563 次 |
最近记录: |