OAuth2 and Google API: access token expiration time?

Martin V. picture Martin V. · Dec 13, 2012 · Viewed 119k times · Source

We have a standalone Java application (see "Installed application") which runs periodically and uses Google API (updates some information from customer databases/ldap/...).

To access Google APIs we store username and password in configuration file, which is a security risk and customer does not like that. So we would like to use OAuth2 long-living access token instead.

What`s default expiration time for Google OAuth2 access tokens ?

As we will have only access token in application, app itself cannot refresh it when access token expires.

Personally I think that OAuth2 implementation in this case will not bring any major benefit but let`s focus on main question - default expiration times.

Answer

vlatko picture vlatko · Dec 13, 2012

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

    https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

    This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.