听起来您需要离线访问。您可以使用一次性代码将其交换为可随时使用的刷新令牌。
$('#signinButton').click(function() {
auth2.grantOfflineAccess().then(signInCallback);
});
在响应中,您将拥有一个带有授权码的 JSON 对象:
{"code":"4/yU4cQZTMnnMtetyFcIWNItG32eKxxxgXXX-Z4yyJJJo.4qHskT-UtugceFc0ZRONyF4z7U4UmAI"}
这一次应该在后端完成,并且您应该保留刷新令牌。
您应该使用google-auth-library在后端完成此工作流程。为此,您将使用身份验证代码来获取刷新令牌。但是,由于这是一个离线工作流程,您还需要按照文档说明验证所提供代码的完整性:
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.
await 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 客户端。
查看我的要点以查看工作流程。