why_vincent
why_vincent

Reputation: 2262

Long lived access token for Google OAuth 2.0

I'm building an application that needs to have access to Google Drive and Google Sheets. I want the user to go to https://mydomain.appspot.com/authenticate to go through the Google login flow and authenticate themselves so that the backend receives access tokens for both Google Drive and Google Sheets.

After that I want the backend to be able to access Drive and Sheets without user interaction. For example, I would like a scheduled task to run every hour and retrieve some data from Drive and Sheets. I want the backend to use the token it received when the user authenticated themselves.

Is this possible? I really hope so. I have been looking here and I don't really find anything that can help me. https://developers.google.com/sheets/api/guides/authorizing

The backend is developed in Java and deployed on Google App Engine.

Upvotes: 6

Views: 13517

Answers (2)

jwilleke
jwilleke

Reputation: 10996

You need to setup Offline Access as defined at: https://developers.google.com/identity/protocols/OAuth2WebServer#offline

After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

Upvotes: 1

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116986

A long lived access token is actually called a refresh token. You will need to have your users authenticate your application then you will receive a refresh token. the refresh token can then be used to request a new access token from the Google authentication servers when ever you need.

Note: Do not get yourself side tracked with serviced accounts its not the same thing. You can run automated scripts using a refresh token gained from Oauth2, googles terminology is just a little confusing.

Check out the official google java client library it should handle most of it for you. Using OAuth 2.0 with the Google API Client Library for Java

Upvotes: 7

Related Questions