Skip to content

Instantly share code, notes, and snippets.

Created January 31, 2017 18:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Send a signed JWT to Google, receive an API token
import os
import time
import json
# 3rd party libraries
import requests
import jwt
# Scope must be at least one of:
# Request multiple scopes with a space-delimited string
SCOPE = ""
def getCredentials():
# Get credentials from env variables
# Or file
# Or user input if no vars
email = ''
secret = ''
credential_file = ''
if os.environ.get("GOOGLE_SERVICE_CREDENTIALS", None):
credential_file = os.environ["GOOGLE_SERVICE_CREDENTIALS"]
if os.environ.get("SERVICE_ACCOUNT_EMAIL", None):
email = os.environ["SERVICE_ACCOUNT_EMAIL"]
email = raw_input("Enter service account email address: ")
if os.environ.get("SERVICE_ACCOUNT_SECRET", None):
secret = os.environ["SERVICE_ACCOUNT_SECRET"]
secret = raw_input("Enter service account key: ")
if credential_file:
creds = json.load(open(credential_file, 'r'))
email = creds['client_email']
secret = creds['private_key']
return (email, secret)
def requestToken():
header = {"alg": "RS256", "typ": "JWT"} # Google uses SHA256withRSA
# See
email, secret = getCredentials()
issued = int(time.time())
expires = issued + 3600 # Expires in 1 hour
authorization_url = ""
payload = {"iss": email, # Issuer Claim
"scope": SCOPE,
"aud": authorization_url, # Audience Claim
"exp": expires,
"iat": issued # Issued At Claim
sig = jwt.encode(payload, secret, algorithm="RS256", headers=header)
params = {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": sig}
r =, data=params)
if r.ok:
print r.json()['access_token']
print r.text
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment