流星帐户 - 谷歌令牌到期

时间:2015-09-24 15:03:57

标签: javascript meteor meteor-accounts

我有Accounts-UI配置设置来为谷歌存储离线令牌:

if (Meteor.isClient) {
 Accounts.ui.config({
  requestOfflineToken: { google: true },
  forceApprovalPrompt: { google: true },
  requestPermissions: { google: ["https://mail.google.com/"] }
 });
}

但是,令牌似乎已过期。我假设我需要以某种方式使用refreshToken。我不确定如何使用流星。任何帮助都很可爱。谢谢!

1 个答案:

答案 0 :(得分:2)

我建议使用Google API Node JS客户端刷新您的访问令牌。

https://github.com/google/google-api-nodejs-client/

它可作为服务器端NPM软件包提供,因此您可能希望{Me}应用程序使用this package router.use('/', require('./routes.custom.js'));

使用此npmRequire配置加载最新的packages.json包:

googleapis

然后在您的Meteor服务器代码中,您将能够像这样刷新访问令牌:

ES2015

{
  "googleapis": "2.1.5"
}

以下是在使用Google服务之前如何刷新访问令牌的完整示例。

const GoogleApis = Meteor.npmRequire('googleapis');

function getAccessToken(user) {
  const googleService = user.services.google;
  // is token still valid for the next minute ?
  if (googleService.expiresAt < Date.now() + 60 * 1000) {
    // then just return the currently stored token
    return {
      access_token: googleService.accessToken,
      token_type: 'Bearer',
      id_token: googleService.idToken,
      expiry_date: googleService.expiresAt,
      refresh_token: googleService.refreshToken,
    };
  }
  // fetch google service configuration
  const googleServiceConfig = Accounts.loginServiceConfiguration.findOne({
    service: 'google',
  });
  // declare an Oauth2 client
  const oauth2Client = new GoogleApis.auth.OAuth2(googleServiceConfig.clientId, googleServiceConfig.secret);
  // set the Oauth2 client credentials from the user refresh token
  oauth2Client.setCredentials({
    refresh_token: user.services.google.refreshToken,
  });
  // declare a synchronous version of the oauth2Client method refreshing access tokens
  const refreshAccessTokenSync = Meteor.wrapAsync(oauth2Client.refreshAccessToken, oauth2Client);
  // refresh tokens
  const tokens = refreshAccessTokenSync();
  // update the user document with the fresh token
  Meteor.users.update(user._id, {
    $set: {
      'services.google.accessToken': tokens.access_token,
      'services.google.idToken': tokens.id_token,
      'services.google.expiresAt': tokens.expiry_date,
      'services.google.refreshToken': tokens.refresh_token,
    },
  });
  //
  return tokens;
}