0

google-auth-library根据Google ,我正在使用 Node包在我的 API 服务器上验证 idToken :

await googlelib.verifyIdToken(
                {
                    idToken: myToken,
                    audience: myGoogleClientID, 
                }, 
                (e, pass) => {...}

因为idToken一小时到期,让用户按小时登录会很麻烦。我已经搜索了文档,类OAuth2Client没有. 如何刷新过期的 idToken()?refreshAccessToken()refreshIdToken()

请注意,我使用的唯一 Google API 是身份验证。

4

2 回答 2

2

听起来您需要离线访问。您可以使用一次性代码将其交换为可随时使用的刷新令牌。

$('#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 客户端。

查看我的要点以查看工作流程。

于 2021-06-20T21:35:47.613 回答
0

经过数小时的研究,相信解决方案只是管理我们自己的会话

于 2021-06-15T00:11:50.530 回答