【问题标题】:Google idToken Refresh谷歌 idToken 刷新
【发布时间】:2021-08-30 15:27:50
【问题描述】:

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

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

因为idToken在一小时后过期,所以让用户每小时登录会很麻烦。我搜索了文档,OAuth2Client 类有refreshAccessToken() 没有refreshIdToken()。如何刷新过期的idToken()?

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

【问题讨论】:

    标签: node.js google-api google-oauth google-api-nodejs-client google-auth-library


    【解决方案1】:

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

    $('#signinButton').click(function() {
       auth2.grantOfflineAccess().then(signInCallback);
     });
    

    在响应中,您将有一个带有授权码的 JSON 对象:

    {"code":"4/yU4cQZTMnnMtetyFcIWNItG32eKxxxgXXX-Z4yyJJJo.4qHskT-UtugceFc0ZRONyF4z7U4UmAI"}
    

    这个一次性应该在后端完成,你应该持久化刷新令牌。

    您应该使用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.
        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 客户端。

    查看my gist 以查看工作流程。

    【讨论】:

    • 感谢您的意见。我对 offline 的理解是当互联网不可用时,对吗?但调查它并没有什么坏处。我在哪里可以找到one time code
    • 离线访问是指当用户离线时,您可以代表用户使用谷歌服务。我编辑了答案以添加前端代码。你也可以看看这个要点gist.github.com/flandrade/a943a47e3575fb8805499e18e6b23c07
    • 非常好的细节和信息,绝对是我的另一个选择!谢谢你,再次感谢!
    【解决方案2】:

    经过数小时的研究,相信解决方案只需管理我们的own session

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 2021-04-15
      • 2020-03-12
      相关资源
      最近更新 更多