Skip to content

Instantly share code, notes, and snippets.

@phlbnks
Created January 31, 2023 23:12
Show Gist options
  • Save phlbnks/7172525271bed9f1c483e3d06d9cc4e3 to your computer and use it in GitHub Desktop.
Save phlbnks/7172525271bed9f1c483e3d06d9cc4e3 to your computer and use it in GitHub Desktop.
Script to generate OAuth token file for use with Google API, specifically with parsedmarc / dmarc-visualizer
#!/bin/bash
# Injest / setup vars // TODO: error handling needed
client_id=$( cat parsedmarc/credentials.json | jq -r '.installed.client_id' )
client_secret=$( cat parsedmarc/credentials.json | jq -r '.installed.client_secret' )
scope="https://www.googleapis.com/auth/gmail.modify"
echo
echo "This script will take your OAuth Desktop Application credentials.json and use it to get a token to interact with the API"
sleep 2
# Get authorization code, needs browser/interaction
url="https://accounts.google.com/o/oauth2/auth?client_id=${client_id}&redirect_uri=http://127.0.0.1&scope=${scope}&response_type=code"
echo "Opening your default browser to start OAuth flow"
echo "If this fails, please manually go to the URL: ${url}"
echo "After authorising, you will see a page that doesn't load with the address http://127.0.0.1"
echo "Copy the string between ?code= and &scope= and enter it below"
sleep 5
open ${url}
read -p "Code parameter from URL: " code
# Obtain OAuth Token // TODO: add error handling
token_response=$( curl --silent --request POST --data "code=${code}&client_id=${client_id}&client_secret=${client_secret}&redirect_uri=http://127.0.0.1&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token )
refresh_token=$( jq -r '.refresh_token' <<<"$token_response" )
token=$( jq -r '.access_token' <<<"$token_response" )
# Refresh if needed // TODO: use this... need logic here to check for existing token + fall back to start if refresh fails.
#curl --request POST --data "--data 'client_id=$client_id&client_secret=$client_secret&refresh_token=$refresh_token&grant_type=refresh_token" https://accounts.google.com/o/oauth2/token
# Get status of token
#curl "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=$token"
token_json=$( echo $token_response | jq --arg client_id $client_id --arg client_secret $client_secret '. + {client_id: $client_id, client_secret: $client_secret}' )
echo $token_json > parsedmarc/oauth.token
echo
echo "Complete. Please check parsedmarc/oauth.token"
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment