Google API access token and refresh token

Introduction

The other day, when I used Google's API, I overlooked a Not Found error and a Bad Request error, so I will summarize it as a memo.

Create a project from the Google console

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

Creating API credentials

image.png

1. OAuth client ID

Select this if the user consents to authorization from the screen image.png

After entering the application type, name, and approved redirect URI, a client ID and client secret were generated.

2. Service account key

Get an access token in JSON format behind the scenes without screen operation. Select this for batch processing image.png

Download the file in JSON format

Obtaining an authorization code

Set client and scoop and access from URL

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&
 access_type=offline&
 include_granted_scopes=true&
 redirect_uri=http%3A%2F%2localhost:8080&
 response_type=code&
 client_id=Client ID obtained above

If you agree with Google, you can get the authorization code from the URL. http://localhost:8080/?code=xxxxxxxxxxxx&scope=yyyyyyyyyyy

Obtaining an access token

specification

image.png

image.png

Point 1: POST method. NG with GET method Point 2: Set "Content-Type: application / x-www-form-urlencoded" in the header. NG if not set or JSON is set.

Sample code

Test.java


        String url = "https://www.googleapis.com/oauth2/v4/token";

		CloseableHttpClient httpclient = HttpClients.createDefault();

		HttpPost request = new HttpPost(url);
		List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
		parameters.add(new BasicNameValuePair("code", authorizationCode)); //The authorization code obtained above
		parameters.add(new BasicNameValuePair("client_id", oAuthClientId)); //Client ID for API credentials on the console
		parameters.add(new BasicNameValuePair("client_secret", oAuthClientSecret)); //Client secret of API credentials on the console
		parameters.add(new BasicNameValuePair("redirect_uri", "http://localhost:8080")); //Approved redirect URI that you have set
		parameters.add(new BasicNameValuePair("grant_type", "authorization_code")); //Fixed

		HttpEntity entity = new UrlEncodedFormEntity(parameters);
		request.setEntity(entity);
		
		request.setHeader("Content-Type", "application/x-www-form-urlencoded");

		CloseableHttpResponse response = httpclient.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		    String result = EntityUtils.toString(response.getEntity(), "UTF-8");
		    System.out.println(result);
		}
		response.close();

Response field: image.png

Now that you have the access token, you can get the data from Google. This is an example of setting an access token in the header. curl -H "Authorization: Bearer <access_token>" https://www.googleapis.com/drive/v2/files

Update access token using refresh token

The access token has an expiration date. After a certain period (60 minutes), it becomes invalid. At this time, you may get the authorization code again, It is common to reissue an access token using a refresh token because it is troublesome for the user.

specification

It's the same as an access token. image.png

image.png

Sample code

Test.java


        String url = "https://www.googleapis.com/oauth2/v4/token";

		HttpPost request = new HttpPost(url);
		List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
		parameters.add(new BasicNameValuePair("refresh_token", "xxxxxxx")); //Refresh token you have
		parameters.add(new BasicNameValuePair("client_id", oAuthClientId)); //Client ID for API credentials on the console
		parameters.add(new BasicNameValuePair("client_secret", oAuthClientSecret)); //Client secret of API credentials on the console
		parameters.add(new BasicNameValuePair("redirect_uri", "http://localhost:8080")); //Approved redirect URI that you have set
		parameters.add(new BasicNameValuePair("grant_type", "refresh_token")); //Fixed

		HttpEntity entity = new UrlEncodedFormEntity(parameters);
		request.setEntity(entity);
		
		request.setHeader("Content-Type", "application/x-www-form-urlencoded");

		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = httpclient.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		    String result = EntityUtils.toString(response.getEntity(), "UTF-8");
		    System.out.println(result);
		}
		response.close();

This is an example response. image.png

As shown in the sample, there is no refresh token, so if the refresh token is also invalid, you will have to start over from obtaining the authorization code.

Reference URL: https://developers.google.com/identity/protocols/OAuth2WebServer

that's all

Recommended Posts

Google API access token and refresh token
Grant an access token with the curl command and POST the API
Get an access token for the Pocket API
Google App Engine Datastore and Search API integration
Gurunavi API access method
Book registration easily with Google Books API and Rails
Speech transcription procedure using Python and Google Cloud Speech API
[LINE Messaging API] Issue channel access token v2.1 in Python
Beginners of Google Maps API and Twitter API made "tweet map"
Zabbix API this and that
Access Google Drive with Python
Google Drive Api Tips (Python)
Obtaining Azure Access Token by Python for using Microsoft Graph API
Get conversions and revenue with Google Analytics API and report to Slack
[Google Maps API] Map is not displayed and becomes blank [Rails]
Firebase Authentication token issuance in Python and token verification with Fast API
[Ruby on Rails] Display and pinning of GoolgeMAP using Google API
I tried using docomo speech recognition API and Google Speech API in Java