Skip to content

Instantly share code, notes, and snippets.

@dccampbell
Last active July 11, 2021 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dccampbell/685e27a65f162584f7935d85a7adce6d to your computer and use it in GitHub Desktop.
Save dccampbell/685e27a65f162584f7935d85a7adce6d to your computer and use it in GitHub Desktop.
Google OAuth 2.0 Walkthrough Script - script to help step through getting an access token for Google API calls (w/o needing a domain/server)
#!/bin/bash
# Variables
client_id=""
client_secret=""
scopes=""
auth_code=""
access_token=""
refresh_token=""
#### Usage ####
## Set whichever variables above that you have so far, leave the rest blank (none is fine).
## The script will print instructions on what to do next based on what you have.
## If enough variables are set, the access_token and refresh_token will be retrieved.
## If access_token is set, it will be validated.
## If refresh_token is set and access_token validation fails, a refresh will be attempted.
###############
# 1) Client/Project Creds
if [[ -z $client_id || -z $client_secret ]]; then
echo 'https://console.developers.google.com/';
echo 'Go to the above URL and register a project w/ relevant APIs...'
echo '...then create an Oauth Consent Screen w/ the appropriate scopes and test users...'
echo '...then create an OAuth Client for a Desktop Application to get the client id and secret.'
exit 1
fi
# 2) OAuth2 Auth Code
if [[ -z $auth_code ]]; then
echo "Go to this URL to complete the OAuth flow to get the auth code: "
echo "https://accounts.google.com/o/oauth2/auth?client_id=$client_id&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=$scopes"
exit 2
fi
# 3) OAuth2 Tokens
if [[ -z $access_token && -z $refresh_token ]]; then
echo "Attempting to get tokens..."
_tokenData="client_id=$client_id&client_secret=$client_secret&code=$auth_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code"
curl --request POST --data $_tokenData "https://accounts.google.com/o/oauth2/token"
exit 0
fi
# 4) Validate Token
if [[ -n $access_token ]]; then
echo "Attempting token validation..."
if curl -f "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=$access_token"; then
echo "Validated Access Token: $access_token"
exit 0
fi
fi
#5) Refresh Tokens
if [[ -n $refresh_token ]]; then
echo "Attempting token refresh..."
_refreshData="client_id=$client_id&client_secret=$client_secret&refresh_token=$refresh_token&grant_type=refresh_token"
curl --request POST --data $_refreshData "https://accounts.google.com/o/oauth2/token"
else
echo "Refresh attempt skipped, no refresh_token set."
exit 3
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment