Google OAuth2 API刷新令牌

时间:2016-04-12 16:09:45

标签: node.js google-api google-api-nodejs-client oauth2

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

我的流程很简单:

1)尝试使用此功能授权客户端:

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)该方法将检查文件中是否存在令牌。如果找不到该文件,则以下函数将创建该文件:

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对象的示例:

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%运行,直到令牌过期。在此之后,我收到“Invalid Credentials”消息。

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

这是获取带有刷新令牌的访问令牌的更新解决方案:

const { google } = require("googleapis");
const OAuth2 = google.auth.OAuth2;

const oauth2Client = new OAuth2(
  "xxxxxxxxx.apps.googleusercontent.com", // ClientID
  "xxxxxxx", // Client Secret
  "https://developers.google.com/oauthplayground" // Redirect URL
);

oauth2Client.setCredentials({
  refresh_token:
    "xxxxxxxx"
});

const accessToken = oauth2Client.getAccessToken();