Thursday, 7 May 2015

Google API Getting OAUTH2 Access Token (Part 1 Create Project and Get Access Token)

This post is aimed at exploring the Google API access through an access token. In order to do so one needs to get the access token and the steps to do so is detailed below.

Step 1: Register An App in Google developer Console

Create a Project in the Google developer console:

Click on the API link and Enable the Required API (In this case I have enabled the Drive API)

Step 2: Create the Client Id
Click on the Credentials tab to navigate to the Create Client Id screen

Click on Create New Client ID.

Select the appropriate application type. In my case I chose Web Application I was using it on a browser for accessing the Google Drive.

Select email id, enter the Product Name and save

On the Create Client Id enter the host from where your application would run. In my case i have entered a localhost url as I am testing the same.

There are two things of importance here:
1) The Authorized Javascript Origin: this is your application url from where all the requests would origin. When the application is granted to access the google API, the request should origin from the domain mentioned in this scree.
2) Authorized redirect URI : This is very important for further processing as during the auth process the browser will redirect to the Google pages for consent where the user accepts the permissions sought by the app (scopes will cover in subsequent blogs). 

Submission of the page creates the client id.

This completes the steps to Creating the Client Id and we are ready proceed towards obtaining a access_token.

3) Fetch the Access Code:

The access token can be fetched directly in the first response, but then the token retrieved has a short life. In order to be able to fetch the access token endlessly it is good to store a reference to the refresh token and use it to fetch all subsequent tokens. 

Request Url :
Parametes : 
client_id : The client id of the app project (as per screenshot it is "")
scope : "openid profile email"  
redirect_uri : The uri defined during the client id creation (https://localhost:3002/oauth2callback)
state : A random string that can be used to identify the request on redirect back from google consent screens
access_type : offline (this indicates that the application requires an offline access which will help in getting the refresh token which can be used to get access token for access till permissions are revoked by the user

Request Code:

var CLIENT_ID = ""
var oauthparams = {};
oauthparams.client_id = CLIENT_ID;
oauthparams.response_type = 'code';
oauthparams.scope = "openid profile email";
oauthparams.redirect_uri = "https://localhost:3002/oauth2callback";
oauthparams.state = "usearandomidlater";
oauthparams.access_type = "offline";
var authurl = "";
var queryparams = $.param(oauthparams);

As you can see the page is redirected to the google auth url with request parameters. Accept the authorization in the page.

On Accepting the page will be redirected back to the redirect url : 
https://localhost:3002/oauth2callback?state=usearandomidlater&code=4/Z6U2Rfdw56GRz_y-4IvXEB3MDEGk0VlQCFduu5S3ayA.4ichVUMhZqodcp7tdiljKKapJNNjmgI&authuser=0&prompt=consent&session_state=84c996f4ae4ad226d8edb0b834b113c88 a5393fd..93b2#

The code retrieved at this stage is very important which can be used in further AJAX calls to retrieve the access token and refresh tokens.

4) Redeem the code to fetch the Access Token:

I have made us of the google API scripts to fetch the access token as it takes care of the required request encoding.

var code = "4/Z6U2Rfdw56GRz_y-4IvXEB3MDEGk0VlQCFduu5S3ayA.4ichVUMhZqodcp7tdiljKKapJNNjmgI";
var CLIENT_ID = "";
var CLIENT_SECRET = "li80cFplMMk1HW2PZ7VxgwPJ";
var request = gapi.client.request({
 path : "/oauth2/v3/token",
 method : 'POST',
 headers : {
  'Content-Type': 'application/x-www-form-urlencoded'
 params : {
  'code' : code,
  'client_id' : CLIENT_ID,
  'client_secret' : CLIENT_SECRET,
  'redirect_uri' : "https://localhost:3002/oauth2callback",
  'grant_type' : 'authorization_code'

When code is first redeemed the refresh token and the access_token is returned and all subsequent request would return only the access_token. To get the access token it is good to store the refresh token.

By sending the following request parameters instead of the one mentioned above. The rest of the process remain same.
'refresh_token' : <refresh token from above request>,
'client_id' : CLIENT_ID,
'client_secret' : CLIENT_SECRET,
'grant_type' : 'refresh_token'

The response would contain the access code(default expiry in 3600s) which can be used in all Google API requests (provided the API has access has been granted). In case any new API request add the same to scope and initiate the consent form request.