首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何从grantOfflineAccess返回的response_code中获取refresh_token

如何从grantOfflineAccess返回的response_code中获取refresh_token
EN

Stack Overflow用户
提问于 2019-02-22 13:08:03
回答 2查看 331关注 0票数 0

我在invalid_grant问题上遇到了麻烦。我引用gapi文档并实现流程,如下所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

EN

回答 2

Stack Overflow用户

发布于 2019-02-22 13:18:36

您从response获得的代码是一次性代码,您的服务器应该将其交换为Access TokenRefresh Token。请参考this

将refresh_token存储在客户端应用程序上并不是最佳做法,因为它不安全。如果你只有客户端应用程序,我建议你关注link

希望能有所帮助。

票数 0
EN

Stack Overflow用户

发布于 2021-06-20 18:43:26

正如Nirav's answer提到的,您需要将此一次性令牌交换为可以随时使用的刷新令牌。

您应该在Node.js后端使用google-auth-library来完成此工作流。为此,您将使用身份验证码来获取刷新令牌。但是,由于这是离线工作流,因此您还需要验证所提供代码作为documentation explains的完整性

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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很有帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54827870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文