Google Auth

2.49.1 · active · verified Sat Mar 28

google-auth is the official Google Authentication Library for Python, providing Application Default Credentials (ADC), service account credentials, OAuth2 tokens, JWT signing/verification, ID token support, Workload Identity Federation, and transport integrations for Requests, urllib3, aiohttp, and gRPC. Current stable version is 2.49.1, released as part of the google-cloud-python monorepo with a roughly monthly cadence.

Warnings

Install

Imports

Quickstart

Demonstrates Application Default Credentials (ADC) via google.auth.default() and explicit service account credentials. Set GOOGLE_APPLICATION_CREDENTIALS to a service account JSON key path, or authenticate locally with `gcloud auth application-default login`.

import os
import google.auth
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from google.auth.exceptions import DefaultCredentialsError

# --- Option 1: Application Default Credentials (recommended for GCP-hosted workloads)
# Set GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json, or run:
#   gcloud auth application-default login
os.environ.setdefault('GOOGLE_APPLICATION_CREDENTIALS', os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''))

try:
    credentials, project = google.auth.default(
        scopes=['https://www.googleapis.com/auth/cloud-platform']
    )
    # Force a token refresh so we can verify auth works
    credentials.refresh(Request())
    print(f'ADC OK — project={project}, token expiry={credentials.expiry}')
except DefaultCredentialsError as e:
    print(f'No credentials found: {e}')

# --- Option 2: Explicit service account key file
key_path = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', '')
if key_path:
    sa_creds = service_account.Credentials.from_service_account_file(
        key_path,
        scopes=['https://www.googleapis.com/auth/cloud-platform'],
    )
    sa_creds.refresh(Request())
    print(f'SA token expiry: {sa_creds.expiry}')

view raw JSON →