Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created February 15, 2023 05:53
Show Gist options
  • Save tanaikech/5196ed237812192539c4369000bc131b to your computer and use it in GitHub Desktop.
Save tanaikech/5196ed237812192539c4369000bc131b to your computer and use it in GitHub Desktop.
Retrieving Access Token from Service Account using oauth2client and google-auth with Python

Retrieving Access Token from Service Account using oauth2client and google-auth with Python

This is a sample script for retrieving the access token from the service account using oauth2client and google-auth with Python.

Sample script 1

Use oauth2client.

from oauth2client.service_account import ServiceAccountCredentials

SERVICE_ACCOUNT_FILE = "credentials.json"
SCOPES = ["https://www.googleapis.com/auth/drive"]

creds = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
res = creds.get_access_token()
access_token = res.access_token

print(access_token)

Sample script 2

Use google-auth. In the current stage, this method might be general.

from google.oauth2 import service_account
import google.auth.transport.requests

SERVICE_ACCOUNT_FILE = "credentials.json"
SCOPES = ["https://www.googleapis.com/auth/drive"]

creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
request = google.auth.transport.requests.Request()
creds.refresh(request)
access_token = creds.token

print(access_token)

References

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