Angular-TypescriptNo Comments

Use Google OAuth 2.0 to access Google APIs

In this article we will discuss how to use Google OAuth 2.0 to get access token for invoking various Google APIs. Access token is a critical parameter for invoking any Google API as it ensures Authentication and Authorization of the user. There are 2 ways to get access token, i.e, the Implicit Grant Model and the Authorization Code Model.

The Implicit Grant Model is easier to implement but with this every time the access token expires, user has to choose account and provide permissions in popup.

The Authorization Code Model is the recommended approach as user has to provide permission only once. In the response, access token and refresh token is received. Once access token expires, refresh token can be used to get a new access token. This approach does not require the permissions popup to be shown every time. The detailed comparison of both the approaches can be found here.

Let’s see how the code looks like for Authorization Model.


Importing the library:-

Import the below script in the html page.

   <script type="text/javascript" src="https://accounts.google.com/gsi/client"></script>


Adding Support for “google.accounts”

In order to use google.accounts in typescript, we need to run the below commmand.

  npm install --save @types/google.accounts


This will add an entry into package.json’s dependencies like below:-

 "@types/google.accounts": "^0.0.7"


Invoking Google Sign In


client.requestCode() is responsible for opening the popup.
In the callback, we are triggering this.retrieveAccessToken(), which will fetch the “access_token”, using the Authorization code received in response.


Retrieve Access Token

  retrieveAccessToken() {
    const accessTokenRequest = this.getAccessTokenRequest();
    this.http.post<AccessTokenResponse>(GOOGLE_OAUTH_ENDPOINT, accessTokenRequest)
      .subscribe((res: AccessTokenResponse) => {
        this.setAccessToken(res.access_token); // The Access token
        this.setRefreshToken(res.refresh_token); //Refresh token is used to fetch a new access token
        this.checkAccessToken();
      });
  }

GOOGLE_OAUTH_ENDPOINT is “https://oauth2.googleapis.com/token”
accessTokenRequest looks like this:-

  getAccessTokenRequest(): AccessTokenRequest {
    return {
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      code: this.getOAuth2Code(), // received from the response of Google Sign-in (previous step)
      grant_type: 'authorization_code',
      redirect_uri: REDIRECT_URI, // available in Google Credentials
    };
  }


res.access_token is used for making Google API calls. Access token has an expiry time of 1 hour. After expiry a new access token needs to be fetched.
res.refresh_token is used to fetch a new access token after expiry, without showing Google Sign-in popup. Refresh token should be stored in long term storage. Its needs to be associated with logged in user. So that without showing Google Sign-in popup we can fetch a new access token.


Use Refresh token to fetch a new Access token

Access token needs to be tracked for expiry, and when expired, a new Access token can be fetched as below:-

 refreshAccessToken() {
    const refreshTokenRequest = this.getRefreshTokenRequest();
    this.http.post<RefreshTokenResponse>(GOOGLE_OAUTH_ENDPOINT, refreshTokenRequest)
      .subscribe((res: RefreshTokenResponse) => {
        this.setAccessToken(res.access_token);
      });
  }


refreshTokenRequest used above, can be created as below:-

  getRefreshTokenRequest(): RefreshTokenRequest {
    return {
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      grant_type: 'refresh_token',
      refresh_token: this.getRefreshToken(), // the Refresh token
    };
  }


To get the complete code refer drive-service.ts


Keep Learning! Stay Sharp!