Skip to content

Instantly share code, notes, and snippets.

@johnboxall
Last active January 12, 2017 22:58
Show Gist options
  • Save johnboxall/9b2410d1c5e1be53e8d0 to your computer and use it in GitHub Desktop.
Save johnboxall/9b2410d1c5e1be53e8d0 to your computer and use it in GitHub Desktop.
A script for generating refresh tokens to used to access Google APIs. Requires `python` + `jq`.
echo 'Google OAuth2'
echo ''
echo 'This script generates refresh token to retrieve an'
echo 'access token, to allows access to Google APIs :)'
echo ''
echo '--> Application Credentials: https://console.developers.google.com/projectselector/apis/credentials'
read -p 'Client ID: ' CLIENT_ID
read -p 'Client Secret: ' CLIENT_SECRET
echo ''
echo '--> Scopes: https://developers.google.com/identity/protocols/googlescopes'
read -p 'Scope: ' SCOPE
echo ''
echo "--> Open https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client_id=${CLIENT_ID}&scope=${SCOPE}"
read -p 'Authorization Code: ' AUTHORIZATION_CODE
echo ''
echo '--> Fetching Refresh Token'
REFRESH_TOKEN=$(curl -sd "code=${AUTHORIZATION_CODE}&client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&grant_type=authorization_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob" \
https://www.googleapis.com/oauth2/v4/token | jq -r '.refresh_token')
echo 'Refresh Token:' $REFRESH_TOKEN
echo ''
echo '--> Fetching New Access Token'
ACCESS_TOKEN=$(curl -sd "refresh_token=${REFRESH_TOKEN}&client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&grant_type=refresh_token" \
https://www.googleapis.com/oauth2/v4/token | jq -r '.access_token')
echo 'Access Token:' $ACCESS_TOKEN
echo ''
echo '--> Fetching Protected Resource'
GROUP='[email protected]'
curl -sH "Authorization: Bearer ${ACCESS_TOKEN}" \
"https://www.googleapis.com/admin/directory/v1/groups/${GROUP}/members"
echo ''
echo 'Now, store that Refresh Token somewhere safe and enjoy!'
@yuraksisa
Copy link

Hi,

I'm getting the following when I try to get the refresh token

{
"error": "redirect_uri_mismatch",
"error_description": "Bad Request"
}

Did you get the same error

Thanks

Juan

@klightspeed
Copy link

klightspeed commented Oct 31, 2016

@yuraksisa when creating the client ID in the Google developer console, you must specify the application as Other in order to have a redirect URI of urn:ietf:wg:oauth:2.0:oob

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment