我在invalid_grant问题上遇到了麻烦。我引用gapi文档并实现流程,如下所示:
var authorisationRequestData =
{
'client_id': clientId,
'scope': scopes,
'immediate': immediate,
prompt: 'consent',
access_type: 'offline',
include_granted_scope: true,
}
const authInstance = gapi.auth2.getAuthInstance();
authInstance.grantOfflineAccess(authorisationRequestData)
.then((res) => {
console.log(gapi.auth.getToken());
var all_token = JSON.stringify(gapi.auth.getToken());
console.log("Token =" + all_token);
console.log(res);
console.log(res.code);
}).catch(error => {
console.log(error);
});
我从上面的实现中获得了访问令牌和response_code,并且能够创建针对用户的日历事件。但1小时后,它给我的错误是,“错误: invalid_grant,代码:400”.Token返回类似于"4/-QA8fj7FyvcPzlVwsapQwyqyKJs0MwkQlNdGhACVgOx3YSP5JamyEplViIx-uSV3JeAHrp9n0RZC0FMSX7IwAQk“的grantOfflineAccess
发布于 2019-02-22 13:18:36
发布于 2021-06-20 18:43:26
正如Nirav's answer提到的,您需要将此一次性令牌交换为可以随时使用的刷新令牌。
您应该在Node.js后端使用google-auth-library来完成此工作流。为此,您将使用身份验证码来获取刷新令牌。但是,由于这是离线工作流,因此您还需要验证所提供代码作为documentation explains的完整性
const { OAuth2Client } = require('google-auth-library');
/**
* Create a new OAuth2Client, and go through the OAuth2 content
* workflow. Return the refresh token.
*/
function getRefreshToken(code, scope) {
return new Promise((resolve, reject) => {
// Create an oAuth client to authorize the API call. Secrets should be
// downloaded from the Google Developers Console.
const oAuth2Client = new OAuth2Client(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope,
});
// Verify the integrity of the idToken through the authentication
// code and use the user information contained in the token
const { tokens } = await client.getToken(code);
const ticket = await client.verifyIdToken({
idToken: tokens.id_token!,
audience: keys.web.client_secret,
});
idInfo = ticket.getPayload();
return tokens.refresh_token;
})
}
有了这个刷新令牌,您就可以随时使用googleapis库创建Google API的客户端。我也在使用这个工作流程来创建事件。对于具有Node.js后端的完整工作流,您可能会发现my gist很有帮助。
https://stackoverflow.com/questions/54827870
复制相似问题