Google OAuth 2: access data from a Google user in your application
Google API authentication with OAuth 2: access data from a Google user in your application-on the example of Gmail
The blog presents how to authenticate and authorize an access to Gmail API from the application.
Nowadays web applications are used very widely for almost every task. But it is difficult to remember separate credentials to each and every application. Also, there can be instances where an application requires to communicate with other applications on behalf of the user. These are the basic problems OAuth tries to address.
As the solution, modern websites are created based on the OAuth protocol with the concepts of “Identity Federation” ( Allowing users to log in to an application with another account.) and “Delegated Authorization” (Allowing another service to access resources on another service on behalf of the user without sharing user’s credentials.).
How does OAuth work?
To understand how OAuth works, we need to understand Roles, grant types, endpoints, access tokens, and refresh tokens.
ROLES
First, we need to understand how it separates the responsibility of our requests. Roles are used to defining the separate entities involved in a request.
THE CLIENT
The client is the application trying to access the user's account and get protected resources. It needs the Authorization to do so. This might be the website you're on, the app you've installed to your phone, or both. In our example, this would be ProjectOauth.
THE RESOURCE SERVER
The resource server is the place storing the user's information. In our example, this would be Gmail.
THE AUTHORIZATION SERVER
This is the server that asks the user to approve or deny the request.
THE RESOURCE OWNER
The resource owner is the person who is giving access to their data. So if you're giving ProjectOauth permission to access your Gmail info, you're the resource owner.
Grant Types
A grant represents the user's permission to access their data and can be used to acquire an access token. The OAuth Specification describes four flows for acquiring an access token. These flows are called grant types. Which one is more suitable for you will most likely depend on the type of client.
Authorization Code: used by Web Apps executing on a server. Use client secret (to store client passwords in a secure place; the server must be needed).
Implicit: The Implicit Grant Type is a way for a single-page JavaScript app to get an access token without an intermediate code exchange step. It was originally created for use by JavaScript apps (which don’t have a way to safely store secrets) but is only recommended in specific situations.
Resource Owner Password Credentials: used by trusted apps from the same vendor. (FaceBook with FaceBookLite APP)
Client Credentials: used for machine to machine communication (server to server communication), such as API auth.
Ex: Weather apps And Cricinfo website
No user interaction and protected data.Only generic data
Endpoints
Redirection Endpoint - This is provided by the Client Application to the service provider. The service provider will send the access tokens etc to this endpoint.
Authorization Endpoint -This is the endpoint the Client Application should use to initiate the Authorization process. This is server side endpoint.
Token Endpoint -This is the endpoint the Client Application should use to initiate Token flow. This is server side endpoint.
Access tokens
Access tokens represent your authorization to access The Resource Owner's information on The Resource Server. You're required to exchange your grant for an access token, which will have an expiry time. Access tokens expire so that any malicious use and damage is limited. You'll need a new access token once it has expired. They can be setup to expire after any amount of time, usually a few minutes.
Refresh tokens
Refresh tokens are a special type of token that can be held securely by The Client with the express purpose of being able to request a new access token from The Authorization Server once the original access token has expired. These can also expire but are generally long lived with expiry times that can be as long as 14 days or more.
The Authorization Server should be able to revoke a refresh token in the event that it could have been compromised.
Scopes
Scopes are what you see on the authorization screens when an app requests permissions. They’re bundles of permissions asked by the client when requesting a token. These are defined by the application developer when creating the application.
To understand how OAuth works, we need to understand Roles, grant types, endpoints, access tokens, and refresh tokens.
ROLES
First, we need to understand how it separates the responsibility of our requests. Roles are used to defining the separate entities involved in a request.
First, we need to understand how it separates the responsibility of our requests. Roles are used to defining the separate entities involved in a request.
THE CLIENT
The client is the application trying to access the user's account and get protected resources. It needs the Authorization to do so. This might be the website you're on, the app you've installed to your phone, or both. In our example, this would be ProjectOauth.
The client is the application trying to access the user's account and get protected resources. It needs the Authorization to do so. This might be the website you're on, the app you've installed to your phone, or both. In our example, this would be ProjectOauth.
THE RESOURCE SERVER
The resource server is the place storing the user's information. In our example, this would be Gmail.
The resource server is the place storing the user's information. In our example, this would be Gmail.
THE AUTHORIZATION SERVER
This is the server that asks the user to approve or deny the request.
This is the server that asks the user to approve or deny the request.
THE RESOURCE OWNER
The resource owner is the person who is giving access to their data. So if you're giving ProjectOauth permission to access your Gmail info, you're the resource owner.
The resource owner is the person who is giving access to their data. So if you're giving ProjectOauth permission to access your Gmail info, you're the resource owner.
Grant Types
A grant represents the user's permission to access their data and can be used to acquire an access token. The OAuth Specification describes four flows for acquiring an access token. These flows are called grant types. Which one is more suitable for you will most likely depend on the type of client.
Authorization Code: used by Web Apps executing on a server. Use client secret (to store client passwords in a secure place; the server must be needed).
Implicit: The Implicit Grant Type is a way for a single-page JavaScript app to get an access token without an intermediate code exchange step. It was originally created for use by JavaScript apps (which don’t have a way to safely store secrets) but is only recommended in specific situations.
Resource Owner Password Credentials: used by trusted apps from the same vendor. (FaceBook with FaceBookLite APP)
Client Credentials: used for machine to machine communication (server to server communication), such as API auth.
Ex: Weather apps And Cricinfo website
No user interaction and protected data.Only generic data
Endpoints
Redirection Endpoint - This is provided by the Client Application to the service provider. The service provider will send the access tokens etc to this endpoint.
Authorization Endpoint -This is the endpoint the Client Application should use to initiate the Authorization process. This is server side endpoint.
Token Endpoint -This is the endpoint the Client Application should use to initiate Token flow. This is server side endpoint.
Access tokens
Access tokens represent your authorization to access The Resource Owner's information on The Resource Server. You're required to exchange your grant for an access token, which will have an expiry time. Access tokens expire so that any malicious use and damage is limited. You'll need a new access token once it has expired. They can be setup to expire after any amount of time, usually a few minutes.
Access tokens represent your authorization to access The Resource Owner's information on The Resource Server. You're required to exchange your grant for an access token, which will have an expiry time. Access tokens expire so that any malicious use and damage is limited. You'll need a new access token once it has expired. They can be setup to expire after any amount of time, usually a few minutes.
Refresh tokens
Refresh tokens are a special type of token that can be held securely by The Client with the express purpose of being able to request a new access token from The Authorization Server once the original access token has expired. These can also expire but are generally long lived with expiry times that can be as long as 14 days or more.
Refresh tokens are a special type of token that can be held securely by The Client with the express purpose of being able to request a new access token from The Authorization Server once the original access token has expired. These can also expire but are generally long lived with expiry times that can be as long as 14 days or more.
The Authorization Server should be able to revoke a refresh token in the event that it could have been compromised.
Scopes
Scopes are what you see on the authorization screens when an app requests permissions. They’re bundles of permissions asked by the client when requesting a token. These are defined by the application developer when creating the application.
Google gives us an access to lots of welfare with the Google API. The API enables to use Google services from our own applications. For example, our apps can exchange data with google drive, use Gmail, calendar, Blogger, ask for analytical data from YouTube. Besides that, there are lots of google cloud services that are available to use. Each API has its own big free quota which allows to reliably rely on Google services. The full list of APIs is available here.
Let’s start to use Google API. Log into your google account and go through the steps.
Now let’s look at our application.
To implement some of the OAuth flows, We need to use the client password, and this must be kept in a secure place. So we may need a server.
This means we cannot implement some flows if we don’t have a server. The applications that don’t need a server ( to be served) are Single Page Application and the application that runs on a user device: Mobile and Desktop app.
Here sample application is a Single Page node application and we use Implicit grant Type to obtain the access token.
Implicit Grant Type Flow
1. The application starts the flow by directing the user agent of the resource owner to the authorization endpoint.
Authorization Request includes its client ID, requested scope, local state, a redirection URI and ‘token’ as the response type. The authorization server sends the user agent back to the redirection URI after access is granted or denied.
2. The authorization server authenticates the resource owner through the user agent and establishes whether the resource owner grants or denies the access request.
3. If the user grants consent, OAuth Server redirects the user-agent to the redirect URI provided by the Client Application that contains a URI fragment containing the access token.
4. User-agent follows the redirect URI retaining the access token.
5. The application sends a script to the user agent that can extract the access token.
6. User-agent runs the script and returns the token to the Application.

Access_token is immediately returned to the client after the user login, in an implicit way.
During the initial redirect to the Authorization server, the value of the parameter response_type is token. This means the type of response from the server will be (immediately) an access_token.
In this way, you’ll have one step fewer to execute for the client, but also less secure, because the whole flow is executed on the browser (or user-agent), including the token is transported.
Step 1-Registering the Client App in Google Developer Website
The first step is to create an application in the developer account on Google. Visit https://console.developers.google.com/and add a new application.
Provide a name for your application and then submit the form.
Once your app is created, to access this using OAuth, we need an AppID and App Secret. For that, select ‘Create Credentials’ (which locates at the left corner)and fill out the below data related to your application. I run my app on localhost port 3000, so I put that as my home page URL http://localhost:3000. TheAuthorization callback URL is where the user should be redirected to after the authorization as http://localhost:3000/oauth/auth. After filling the form click Create Button.
Below images are shown generated credentials for our application.
By selecting the application from the above pages, you can find the Client ID and Secret key which are needed to implement the OAuth flow.
With the Client ID and Client Secret, your application can connect to your Google Project.
Now we have successfully registered our app in google and configured it. You need to take down the App ID and App Secret which is generated for your app and also the Redirection Endpoint URL which you defined where we will use these three values in next steps when making requests to Google for retrieving user resources.
Step 2 — Obtaining the Authorization Token
In order to obtain the authorization token from Google, we need to send HTTP GET request to the Authorize Endpoint of Google, which is https://accounts.google.com/o/oauth2/v2/auth. Along with the request, you need to send several parameters which are described below.
Authorization Request
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format.
response_type
REQUIRED. The value MUST be set to "token".
client_id
REQUIRED. (The client identifier) The App ID value of your application
redirect_uri
OPTIONAL. The redirection endpoint URL which we defined in earlier when generating the credentials. This value should be URL encoded when sending with the request.
Scope
OPTIONAL. The scopes (permissions to resources) which your app needs to access. When you have multiple scopes, separate them with spaces and the string should be URL encoded when sending with the request.
State
RECOMMENDED. An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery.
If you are not logged into Google in the browser, first it will ask you to log in.
Once you log in, it will show the following popup which is called the “User Consent Page”. In there, it will show what are the resources from the user account that this external app would be able to access on behalf of you.
1. Login Page 2.Google Sign in Page 3.User Consent Page
Once you Continue, Google will redirect the browser to the Redirection Endpoint URL which you defined and along with the URL, it will send the query parameter access token.
Next, let’s look at how we can use this access token to query Google APIs.
The homepage is displayed New arrivals of Fashion Styles depending on the logged user’s gender and display currently logged username.
Token Revocation with SignOut Button
When user signouts from the app, access token revocation is called.
The client constructs the request by including the following parameters using the "application/x-www-form-urlencoded" format in the HTTP request entity-body:
token REQUIRED. The token that the client wants to get revoked.
token_type_hint OPTIONAL.
Revocation Response
The authorization server responds with HTTP status code 200 if the token has been revoked successfully or if the client submitted an invalid token.
Google gives us an access to lots of welfare with the Google API. The API enables to use Google services from our own applications. For example, our apps can exchange data with google drive, use Gmail, calendar, Blogger, ask for analytical data from YouTube. Besides that, there are lots of google cloud services that are available to use. Each API has its own big free quota which allows to reliably rely on Google services. The full list of APIs is available here.

Access_token is immediately returned to the client after the user login, in an implicit way.
During the initial redirect to the Authorization server, the value of the parameter response_type is token. This means the type of response from the server will be (immediately) an access_token.
In this way, you’ll have one step fewer to execute for the client, but also less secure, because the whole flow is executed on the browser (or user-agent), including the token is transported.
Step 1-Registering the Client App in Google Developer Website
The first step is to create an application in the developer account on Google. Visit https://console.developers.google.com/and add a new application.
Provide a name for your application and then submit the form.
Once your app is created, to access this using OAuth, we need an AppID and App Secret. For that, select ‘Create Credentials’ (which locates at the left corner)and fill out the below data related to your application. I run my app on localhost port 3000, so I put that as my home page URL http://localhost:3000. TheAuthorization callback URL is where the user should be redirected to after the authorization as http://localhost:3000/oauth/auth. After filling the form click Create Button.
Once you Continue, Google will redirect the browser to the Redirection Endpoint URL which you defined and along with the URL, it will send the query parameter access token.
Provide a name for your application and then submit the form.
Once your app is created, to access this using OAuth, we need an AppID and App Secret. For that, select ‘Create Credentials’ (which locates at the left corner)and fill out the below data related to your application. I run my app on localhost port 3000, so I put that as my home page URL http://localhost:3000. TheAuthorization callback URL is where the user should be redirected to after the authorization as http://localhost:3000/oauth/auth. After filling the form click Create Button.
Below images are shown generated credentials for our application.
By selecting the application from the above pages, you can find the Client ID and Secret key which are needed to implement the OAuth flow.
With the Client ID and Client Secret, your application can connect to your Google Project.
Now we have successfully registered our app in google and configured it. You need to take down the App ID and App Secret which is generated for your app and also the Redirection Endpoint URL which you defined where we will use these three values in next steps when making requests to Google for retrieving user resources.
Step 2 — Obtaining the Authorization Token
In order to obtain the authorization token from Google, we need to send HTTP GET request to the Authorize Endpoint of Google, which is https://accounts.google.com/o/oauth2/v2/auth. Along with the request, you need to send several parameters which are described below.
Authorization Request
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format.
response_type
REQUIRED. The value MUST be set to "token".
client_id
REQUIRED. (The client identifier) The App ID value of your application
redirect_uri
OPTIONAL. The redirection endpoint URL which we defined in earlier when generating the credentials. This value should be URL encoded when sending with the request.
Scope
OPTIONAL. The scopes (permissions to resources) which your app needs to access. When you have multiple scopes, separate them with spaces and the string should be URL encoded when sending with the request.
State
RECOMMENDED. An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery.
If you are not logged into Google in the browser, first it will ask you to log in.
Once you log in, it will show the following popup which is called the “User Consent Page”. In there, it will show what are the resources from the user account that this external app would be able to access on behalf of you.
| 1. Login Page 2.Google Sign in Page 3.User Consent Page |
Next, let’s look at how we can use this access token to query Google APIs.
The homepage is displayed New arrivals of Fashion Styles depending on the logged user’s gender and display currently logged username.
Token Revocation with SignOut Button
When user signouts from the app, access token revocation is called.
The client constructs the request by including the following parameters using the "application/x-www-form-urlencoded" format in the HTTP request entity-body:
token REQUIRED. The token that the client wants to get revoked.
token_type_hint OPTIONAL.
Revocation Response
The authorization server responds with HTTP status code 200 if the token has been revoked successfully or if the client submitted an invalid token.










Comments
Post a Comment