Search code examples
apiauthenticationoauth-2.0authorizationaccess-token

Google Identity Services : How to refresh access_token for Google API after one hour?


I have implemented the new Google Identity Services to get an access_token to call the Youtube API. I try to use this on an Angular app.

this.tokenClient = google.accounts.oauth2.initTokenClient({
  client_id: googleApiClientId,
  scope: 'https://www.googleapis.com/auth/youtube.readonly',
  callback: (tokenResponse) => {
    this.accessToken = tokenResponse.access_token;
  },
});

When I call this.tokenClient.requestAccessToken(), I can get an access token and use the Youtube API, that works.

But after one hour, this token expires. I have this error : "Request had invalid authentication credentials."

How can I get the newly refreshed access_token transparently for the user ?


Solution

  • To refresh the access token in a transparent way for the end-user you have to use the Refresh Token, This token will also come in the response to your call.

    With this token, you can do a POST call to the URL: https://www.googleapis.com/oauth2/v4/token with the following request body

    client_id: <YOUR_CLIENT_ID>
    client_secret: <YOUR_CLIENT_SECRET>
    refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
    grant_type: refresh_token
    

    refresh token never expires so you can use it any number of times. The response will be a JSON like this:

    {
      "access_token": "your refreshed access token",
      "expires_in": 3599,
      "scope": "Set of scope which you have given",
      "token_type": "Bearer"
    }