Google OAuth2 API 刷新令牌 [英] Google OAuth2 API Refresh Tokens

查看:44
本文介绍了Google OAuth2 API 刷新令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 google-auth-library-nodejs 库集成到多个 GMail 帐户中,以获取电子邮件列表.

I'm using the google-auth-library-nodejs library to integrate into a number of GMail accounts, to get lists of emails.

我的流程很简单:

1) 尝试授权客户端,使用这个函数:

1) Try to authorize the client, using this function:

function _authorise(mailBox, callback) {
  let auth = new googleAuth();

  let clientId = eval(`process.env.GMAIL_API_CLIENT_ID_${mailBox.toUpperCase()}`);
  let clientSecret = eval(`process.env.GMAIL_API_CLIENT_SECRET_${mailBox.toUpperCase()}`);
  let redirectUri = eval(`process.env.GMAIL_API_REDIRECT_URI_${mailBox.toUpperCase()}`);
  let tokenFile = process.env.GMAIL_API_TOKEN_PATH + mailBox.toLowerCase()+ process.env.GMAIL_API_TOKEN_BASE_FILE_NAME;

  let oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUri);
  fs.readFile(tokenFile, ((err, token) => {
    if (err) {
      _getNewToken(mailBox,oauth2Client,callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  }))
}

2) 该方法将检查文件中是否存在令牌.如果未找到该文件,以下函数将创建该文件:

2) The method will check for existence of a token in a file. If the file is NOT found, the following functions will create the file:

function _getNewToken(mailBox, oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: process.env.GMAIL_API_SCOPES
  });
  console.log('To authorize this app, please use this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', ((code) => {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      _storeToken(mailBox,token);
      callback(oauth2Client);
    });
  }));
}

function _storeToken(mailBox, token) {
  let tokenFile = process.env.GMAIL_API_TOKEN_PATH + mailBox.toLowerCase()+ process.env.GMAIL_API_TOKEN_BASE_FILE_NAME;
  fs.writeFile(tokenFile, JSON.stringify(token));
}

我使用 https://www.googleapis.com/auth/gmail.readonly 作为范围.

这是创建的文件示例:

{"access_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","token_type":"Bearer","refresh_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","expiry_date":1460509994081}

处理后,这是返回的 auth 对象示例:

When processed, here's a sample of the auth object that is returned:

OAuth2Client {
  transporter: DefaultTransporter {},
  clientId_: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
  clientSecret_: 'xxxxxxxxxxxxxxxxxxxxxxxx',
  redirectUri_: 'urn:ietf:wg:oauth:2.0:oob',
  opts: {},
  credentials: {
access_token: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
     token_type: 'Bearer',
     refresh_token: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
     expiry_date: 1460509994081
  }
}

如果我删除文件,并通过手动同意流程,那么身份验证将 100% 有效,直到令牌过期.在此之后,我收到无效凭据"消息.

If I delete the file, and go through the manual consent process, then the authentication works 100%, until the token expires. After this, I get the "Invalid Credentials" message.

我的假设是,一旦令牌过期,刷新令牌将用于自动重新创建访问令牌.我错过了什么吗?

My assumption is that once the token expires, that the refresh token will be used to auto recreate the access token. Am I missing something?

推荐答案

好的,所以我发现了 getAccessToken 方法,它会检查 access_token 并使用它, 除非它已经过期,在这种情况下它会使用 refresh_token 来生成一个新的 access_token.

Okay, so I have discovered the getAccessToken method, which will check the access_token, and use it, unless it has expired, in which case it will use the refresh_token to generate a new access_token.

这篇关于Google OAuth2 API 刷新令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆