April 14, 2021; Updated on

Bash Scripting to Obtain Access Token from Google Authorization Server

I am trying to simplify the process of updating posts on this blog. In this post, to update them using the Blogger API, I create a Bash script that supports the OAuth 2.0 authorization sequence used in Google APIs and obtains an access token from the Google Authorization Server.

Obtain Client Credentials from Google API Console

First, create client credentials with an OAuth client ID for your script in the Google API Console. In this post, I selected the “Desktop app” application type.

Obtain Tokens from Google Authorization Server

Next, receive a single-use authorization code using the authorization URL below. In this post, the redirect URI is http://localhost because I manually copy the code, and the scope is https://www.googleapis.com/auth/blogger. Then, use the client ID of the client credentials in the previous section. Accessing this URL in your browser returns a URL with the code=CODE parameter in the address bar.

https://accounts.google.com/o/oauth2/v2/auth?client_id=$client_id&redirect_uri=http://localhost&response_type=code&scope=$scope

Finally, to exchange this authorization code for your access token and refresh token, request it from the Google Authorization Server using the client credentials. In this post, I use curl for HTTP requests and jq to filter JSON responses.

curl -d client_id=$client_id \
    -d client_secret=$client_secret \
    -d code=$authorization_code \
    -d grant_type=authorization_code \
    -d redirect_uri=http://localhost \
    -X POST https://oauth2.googleapis.com/token |
    jq -r '.access_token, .refresh_token'

Once you have an access token, you can use the Google API by sending this token.

Refresh Access Token If Necessary

If the access token expires, refresh it using the refresh token in the previous section.

curl -d client_id=$client_id \
    -d client_secret=$client_secret \
    -d grant_type=refresh_token \
    -d refresh_token=$refresh_token \
    -X POST https://oauth2.googleapis.com/token |
    jq -r .access_token

Bash Script Example

Combining the above processes, you can authorize your script and obtain an access token from the Google Authorization Server. In a real-world application, I have published the google_oauth_token.sh Bash script on GitHub.

No comments:

Post a Comment