How to use Google Contacts API in meteor?

2019-04-02 21:44发布

I am using meteor to create a webpage with a dropdown list of Google Groups to select from and once selected, the Google contacts will be displayed.

I am using HTTP.call POST to Google's API and testing with the accessToken from mongoDB but when I use that token after some time it expires. I looked into implementing an authentication flow but it is getting very complicated since there is no sample code on Google for meteor. I am new to nodeJS, Javascript and Meteor. Am I going about this the wrong way? How would I implement this in meteor?

https://developers.google.com/accounts/docs/OAuth2?csw=1#expiration

2条回答
冷血范
2楼-- · 2019-04-02 22:21

To deal with the expiration of the accessToken, you will need to obtain the refreshToken from Google. With this refreshToken, you can obtain a new accessToken whenever necessary via a simple HTTP POST to Google's API. Here is the relevant documentation from Google. To obtain the refreshToken, you will need to request for offline access and may also need to force the approval prompt, as detailed in this SO post.

forceApprovalPrompt: {google: true},
requestOfflineToken: {google: true},

I recommend achieving all of the above using Meteor's HTTP package. All the tools are there. You've probably already figured it out:

  var result = HTTP.post(
    "https://www.googleapis.com/oauth2/v3/token",
    {
      params: {
        'client_id': config.clientId,
        'client_secret': config.secret,
        'refresh_token': user.services.google.refreshToken,
        'grant_type': 'refresh_token'
      }
  });

  //Do some error checking here

  var newAccessToken = result.data.access_token;
  1. refresh_token - The refresh token returned from the authorization code exchange.
  2. client_id - The client ID obtained from the Developers Console.
  3. client_secret - The client secret obtained from the Developers Console.
  4. grant_type - As defined in the OAuth 2.0 specification, this field must contain a value of refresh_token.
  5. result.data will be a JSON object with the following

    { "access_token":"1/fFBGRNJru1FQd44AzqT3Zg", "expires_in":3920, "token_type":"Bearer", }

查看更多
ら.Afraid
3楼-- · 2019-04-02 22:22

Have a look at this package its a little wrapper that does auto refresh for you: here

I actually ended up building my own auth flow for with oauth handler because i needed to move away from a tokens linked to user profiles.

查看更多
登录 后发表回答