techie
techie

Reputation: 13

How to use a Refresh token to get access to google drive files

I am using the Drive API and the Google Sheets API to list users private and public spreadsheets using Google Console app.

I want the user to log in to our app the first time to view their files (this process is working). Now I want this user can access his files list without login after first-time authorization.

According to the Google guide, for this, I need to generate the access token and refresh token. I am having both the access token and refresh token. here:

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
  "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

Now how I can use the refresh token and access token for users to avoid login in again and again. Please give a step-by-step process.

Upvotes: 0

Views: 1378

Answers (2)

Christian
Christian

Reputation: 5521

The general Google API docs just say:

Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.

See https://developers.google.com/identity/protocols/oauth2?hl=en

Here's a step by step instruction available for the playground: https://github.com/ivanvermeyen/laravel-google-drive-demo/blob/master/README/2-getting-your-refresh-token.md

Please have a look at this SO question/answer. An answer in this URL provides the following code:

window.gapi.client.init({
  apiKey: this.GOOGLE.API_KEY,
  clientId: this.GOOGLE.CLIENT_ID,
  discoveryDocs: DISCOVERY_DOCS,
  scope: SCOPES
}).then(()=>{
  const authInstance = window.gapi.auth2.getAuthInstance();
  authInstance.grantOfflineAccess()
   .then((res) => {
      console.log(res);
      this.data.refreshToken = res.code;
   });
});

Upvotes: 0

Aman Anand
Aman Anand

Reputation: 11

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
  "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

With the access_token you can get data from your google APIs. The token is specific to the API you have got it from. Use it as Authorization: Bearer 1/fFAGRNJru1FTz70BzhT3Zg).

You can use the refresh token to renew the access token. Access tokens expire after some time (3920 secs in your case).

Upvotes: 1

Related Questions