Skip to content

Instantly share code, notes, and snippets.

@skion
Created March 14, 2023 11:52
Show Gist options
  • Save skion/c5f904546845ac02e2d90061357f30e4 to your computer and use it in GitHub Desktop.
Save skion/c5f904546845ac02e2d90061357f30e4 to your computer and use it in GitHub Desktop.
Obtain an access token for a Google Service Account.
"""
Given a credentials file for a Google Service Account, obtain a short-lived
access token to access Google APIs. Such an access token can be used, for instance,
by a customer to upload external files to a Google Cloud Storage Bucket over HTTP.
To install required dependencies on Debian-based systems:
apt-get install python3-jwt python3-requests
or on other systems:
pip install PyJWT requests
"""
import json
import pathlib
import time
import jwt
import requests
SCOPES = "https://www.googleapis.com/auth/devstorage.read_write"
current_time = int(time.time())
# Read the Google service account JSON file.
service_account = json.load(pathlib.Path("fynch-service-account.json").open("r"))
# Construct assertion payload to exchange for an access token.
payload = {
"iss": service_account["client_email"],
"aud": service_account["token_uri"],
"scope": SCOPES,
"exp": current_time + 60,
"iat": current_time,
}
# Sign assertion, proving that we have access to the service account's private key.
assertion = jwt.encode(
payload=payload, algorithm="RS256", key=service_account["private_key"]
)
# Construct the HTTP request body for the token endpoint.
data = {
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}
res = requests.post(url=service_account["token_uri"], data=data)
res = res.json()
print(res["expires_in"])
print(res["access_token"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment