Skip to content

Instantly share code, notes, and snippets.

@lewisrodgers
Last active December 29, 2017 14:41
Show Gist options
  • Save lewisrodgers/cdaa375f16941f3e1e03cc95338df506 to your computer and use it in GitHub Desktop.
Save lewisrodgers/cdaa375f16941f3e1e03cc95338df506 to your computer and use it in GitHub Desktop.
Retrieve OAuth 2.0 access and refresh tokens for Google Cloud Platform
#!/bin/bash
# This script generates a `tokens.json` file.
#
# example:
# {
# "access_token" : "ya29.Glst...",
# "expires_in" : 3600,
# "refresh_token" : "1/dd3t...",
# "token_type" : "Bearer"
# }
#
# You can then use the `access_token` or `refresh_token` to make calls to a Google API.
#
# usage:
# $ ./get_tokens.sh <code>
#
# First, get a set of OAuth 2.0 credentials for an "installed" application type:
# See: https://developer.chrome.com/webstore/using_webstore_api#beforeyoubegin
#
# 1. Visit the Google Developers Console.
# 2. Create a new project or select an existing one.
# 3. In the sidebar on the left, select APIs & auth.
# 4. In the sidebar on the left, select Credentials.
# 5. Find the lines labeled Client ID and Client secret. Note that there may be a client ID without a client secret for use with Compute Engine and App Engine. In that case, create a new client ID and client secret.
# 6. To create the client ID and client secret, click on Create New Client ID, select Installed Application, and Other under Installed application type.
# 7. Download the json file
#
# This is the path to the file you downloaded.
CREDENTIALS="path/to/secrets"
# Once you have a client ID, you can retrieve a code from Google.
# Enter this URL in your browser, replacing the $CLIENT_ID with the one from your json file:
# https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.googleapis.com/auth/chromewebstore&client_id=$CLIENT_ID&redirect_uri=urn:ietf:wg:oauth:2.0:oob
#
# Provide the code as a command line argument when running this script.
CODE=$1
# Ensure jq is installed on your system: https://stedolan.github.io/jq/
CLIENT_ID=`jq -r ".installed.client_id" $CREDENTIALS`
CLIENT_SECRET=`jq -r ".installed.client_secret" $CREDENTIALS`
# Finally, exchange the code for the tokens and write the reponse to a json file.
curl "https://accounts.google.com/o/oauth2/token" -d \
"client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&code=${CODE}&grant_type=authorization_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob" >> tokens.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment