How to Consume Gmail API using OAuth 2.0 Protocol

Dharshika Singarathnam
5 min readSep 23, 2019

--

Hey guys! In this post you will learn how to consume a Gmail API using OAuth 2.0. If you are beginner to OAuth concept please refer my previous post linked follow Introduction to OAuth2.0 Protocol.

OAuth 2.0

Step I: Registering the Application

1. Create a New Project by clicking “Select a project”.

Create a New Project using Google API Console

2. Enter your project name, and agree with T&C.

Enter the project name and create a New Project

3. Enable the Gmail API to your Newly Created Project.

Enable Gmail API to the project

4. Click on “OAuth consent screen”. Fill out the mandatory fields. Save it.

Fill out the mandatory fields on OAuth consent screen

5. Click on “Create Credentials”. Choose “OAuth Client ID” as the type.

Create Credentials by clicking Create Credentials button (Select OAuth Client ID as type)

6. Fill out the name and Application type should be “Web application”.

7. Add a redirect url in the section Authorised redirect URIs. This url should point to your redirect url script.

8. Click on “Create” button.

Create OAuth Client ID

9. On success your Client Credentials will be generated as follow.

Generated Client Credentials

10. You can view the generated Client id and Client Secret Keys for your Application.

View Created Client Credentials for your Application

Step II: Building the Client Application

First, the user must be redirected to the Google sign-in page to authorize our application. For this purpose, our application must redirect the users to the authorization endpoint.

Initial Page displayed when the application runs on port localhost:8080

After clicking “Open my mail” button the user will be redirected to the authorization endpoint, and the following page will be displayed.

Login
Consent Page

Google’s Authorization Endpoint

Example Endpoint :

GET https://accounts.google.com/o/oauth2/auth?redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&prompt=consent&response_type=code&client_id=xxxxxxxxxxxxx&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly&access_type=offline&state=1234e

Query Parameters

redirect_uri — Determine how Google’s authorization server will respond to your app. You have set up your authorization credentials with a particular redirect method in mind.

response_type — Determines if the Google OAuth 2.0 endpoint returns an authorization code. Set the parameter value to code for installed applications.

client_id — The client ID for your application. You can find this value in the API Console.

scope —A space-separated list of areas that list the resources your application can access on behalf of the user. These values ​​inform the user of the consent screen that Google displays to the user.

prompt — A space-delimited, case-sensitive list of prompts to present the user. If you do not specify this parameter, the user will only be prompted when your app requests access for the first time. Since we need the user to login, and provide consent for our application to access the scope specified, we will use ‘consent’.

access_type —Indicates whether your application can update access tokens if the user does not exist in the browser.

state —Specifies any string value that your application uses to maintain the status between your authorization request and the authorization server’s response.The server returns the exact value that you send as a name=value pair in the hash (#) fragment of the redirect_uri after the user consents to or denies your application's access request.

Implementation

1. The endpoint implementation

After user has given his/her consent, the previously specified redirect_uri receives the authorization code. As a rule, these code values ​​are short-lived. We’ll have to deal with how the callback endpoint (which we’ve specified as redirect_uri) extracts that code and requests the token. This endpoint is implemented by the callback () method in the AuthController.

AuthController.java

2. Obtain the Access Token

In the callback () method that implements the / callback endpoint, the code is extracted from the query parameter and the previously added status parameter will also be a query parameter. Then we will create the token request to POST https://www.googleapis.com/oauth2/v3/token and specify the following parameters in the body as URL Encoded form data.

code — Code received by Google OAuth

client_id — Client ID obtained from the API console

client_secret — Client Secret obtained from the API console

redirect_uri — Same redirect_uri as before, and must match the URL specified in the API console

grant_type — This value must be authorization_code

Once this call is successfully completed, you will receive the access token, refresh token, expiration time, etc. as a JSON response.

{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer",
"refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

This specifies the expiration time for the access token. Once it has expired, the refresh token can be used to get a new access token. If the refresh token is lost, the user must retrace the flow from the consent page to obtain an access token.Once this is done, we’ll safely store the access token and refresh token. .

3. Consuming the API with the Access Token

To search a Google API for user data, you must add the access token that you received in the requirements authorization header.

Implementation of Email Service

After successfully received the access-token user will be redirected to the app home page with the user data as follow.

Home Page

For more information about the endpoints, see the Gmail API documentation and about the OAuth process, see the Google OAuth documentation.The full implementation of the sample application can be found here.

See you soon with the next blog post !

--

--