Using OAuth 2.0 to Access Google APIs | How to generate oauth token ?

All requests to the Google API must be authorized by an authenticated user. To access any of the google product you need oAuth token.

Authorizing requests with OAuth 2.0:

Setup your appliacation:

Go to below link and setup your application, Once application is create get your OAuth client ID

https://console.developers.google.com/apis/dashboard

Get access Code:

To get a code, you need to run a server. Install tomcat and run a simple dynamic application with only homepage.
Let think application is running on http://localhost/

Create below url and open it on chrome: 

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/blogger&response_type=code&access_type=offline&redirect_uri=http://localhost&client_id=YourClientID

Login With valid google account, Once you are Login successfully. It will redirect to localhost with code.

http://localhost/?code=4/2AGswerwyro2KlmBXgXV8A73877482hsjdfhsj7AAtTERUCut7VD_Ty2gVlIlGMyD5xTxBFcYudifu7847&scope=https://www.googleapis.com/auth/blogger

Copy the code and Open postman and any rest api.

Do rest call with below parameters.



Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob%3Aauto&
grant_type=authorization_code

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

access_token is your Authorization token. Use it for google api call.

GET https://www.googleapis.com/blogger/v3/users/self/blogs
Authorization: /* OAuth 2.0 token here */

Example:

GET https://www.googleapis.com/blogger/v3/users/self/blogs
Authorization: Bearer 1/fFAGRNJru1FTz70BzhT3Zg

Java APi call: Sending GET request with Authentication headers


HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);

HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String result = restTemplate.postForObject(url, entity, String.class);

You can use it for all google products like blogger, Drive, YouTube, Gmail, Map, news ect.

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Object oriented programming concepts (OOPs)

Spring Boot and Vaadin : Filtering rows in Vaadin Grid