问题描述
我正在尝试在 node.js 上使用 google api,但总是出现以下错误:
I'm trying to use the google api on node.js, but I always have the following error:
invalid_grant
Malformed auth code
通过在网络上搜索,我发现客户端 ID 应该是电子邮件地址,而不是控制台上的客户端 ID.我将其更改为我的 google 帐户的电子邮件地址,情况更糟,因为我无法使用 google 进行连接
By searching on the web I saw that the client id should be an email address, not the client id on the console. I changed that to the email address of my google account, it was even worse because I wasn't able to connect using google
这是改编自 https://developers.google.com 的代码/youtube/v3/docs/videos/list
var fs = require('fs');
var readline = require('readline');
var { google } = require('googleapis');
// var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/google-apis-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'google-apis-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the YouTube API.
//See full code sample for authorize() function code.
authorize(JSON.parse(content), {'params': {'id': 'Ks-_Mh1QhMc',
'part': 'snippet,contentDetails,statistics'}}, videosListById);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, requestData, callback) {
// Regarder response.config.data
var clientSecret = credentials.client_secret;
var clientId = credentials.client_id;
var redirectUrl = credentials.redirect_uri;
var auth = google.auth.OAuth2;
var oauth2Client = new google.auth.OAuth2(
clientId,
clientSecret,
redirectUrl
);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, requestData, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client, requestData);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, requestData, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token');
console.log(err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client, requestData);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Remove parameters that do not have values.
*
* @param {Object} params A list of key-value pairs representing request
* parameters and their values.
* @return {Object} The params object minus parameters with no values set.
*/
function removeEmptyParameters(params) {
for (var p in params) {
if (!params[p] || params[p] == 'undefined') {
delete params[p];
}
}
return params;
}
/**
* Create a JSON object, representing an API resource, from a list of
* properties and their values.
*
* @param {Object} properties A list of key-value pairs representing resource
* properties and their values.
* @return {Object} A JSON object. The function nests properties based on
* periods (.) in property names.
*/
function createResource(properties) {
var resource = {};
var normalizedProps = properties;
for (var p in properties) {
var value = properties[p];
if (p && p.substr(-2, 2) == '[]') {
var adjustedName = p.replace('[]', '');
if (value) {
normalizedProps[adjustedName] = value.split(',');
}
delete normalizedProps[p];
}
}
for (var p in normalizedProps) {
// Leave properties that don't have values out of inserted resource.
if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {
var propArray = p.split('.');
var ref = resource;
for (var pa = 0; pa < propArray.length; pa++) {
var key = propArray[pa];
if (pa == propArray.length - 1) {
ref[key] = normalizedProps[p];
} else {
ref = ref[key] = ref[key] || {};
}
}
};
}
return resource;
}
function videosListById(auth, requestData) {
var service = google.youtube('v3');
var parameters = removeEmptyParameters(requestData['params']);
parameters['auth'] = auth;
service.videos.list(parameters, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(response);
});
我在控制台中复制粘贴了代码,但仍然出现相同的错误
I literally copy-paste the code in the console, but still have the same error
推荐答案
这是我的情况:
url hash 片段中的授权码正在被encodeURIComponent
API 编码,所以如果你通过这个代码来请求访问令牌.它会抛出一个错误:
The authorization code in the url hash fragment is being encoded by encodeURIComponent
API, so if you pass this code to request the access token. It will throw an error:
{ "error": "invalid_grant", "error_description": "Malformed auth code."}
所以我使用 decodeURIComponent解码授权码.
So I use decodeURIComponent to decode the authorization code.
decodeURIComponent('4%2F_QCXwy-PG5Ub_JTiL7ULaCVb6K-Jsv45c7TPqPsG2-sCPYMTseEtqHWcU_ynqWQJB3Vuw5Ad1etoWqNPBaGvGHY')
解码后的授权码为:
"4/_QCXwy-PG5Ub_JTiL7ULaCVb6K-Jsv45c7TPqPsG2-sCPYMTseEtqHWcU_ynqWQJB3Vuw5Ad1etoWqNPBaGvGHY"
这篇关于Google Api、Node.js - invalid_grant 格式错误的身份验证代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!