Google Authentication Library providing comprehensive authentication mechanisms for Google APIs and services including OAuth 2.0, JWT, and service account credentials
—
Server-to-server authentication using service account keys and JWT tokens. Service accounts are Google accounts associated with your application or compute instance, enabling applications to authenticate and make API calls on their own behalf.
Standard OAuth2 flow using service account keys, supporting token refresh and scope-based access control.
class Credentials(
google.auth.credentials.Scoped,
google.auth.credentials.CredentialsWithQuotaProject
):
"""Service account credentials for OAuth2 authentication."""
def __init__(
self,
signer,
service_account_email,
token_uri,
scopes=None,
default_scopes=None,
subject=None,
project_id=None,
quota_project_id=None,
additional_claims=None,
always_use_jwt_access=False,
universe_domain=google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN,
trust_boundary=None,
**kwargs
):
"""
Initialize service account credentials.
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs
service_account_email (str): The service account email address
token_uri (str): The OAuth 2.0 authorization server's token endpoint URI
scopes (Sequence[str]): User-defined scopes to request
default_scopes (Sequence[str]): Default scopes passed by client libraries
subject (str): For domain-wide delegation, the email address of the user to impersonate
project_id (str): The project ID associated with the service account
quota_project_id (str): The project for quota and billing
additional_claims (Mapping[str, str]): Any additional claims for the JWT assertion
always_use_jwt_access (bool): Whether to always use JWT access tokens
universe_domain (str): The STS audience which contains the resource name
trust_boundary (str): String representation of trust boundary meta
"""
@classmethod
def from_service_account_file(
cls,
filename,
**kwargs
):
"""
Create credentials from a service account JSON file.
Args:
filename (str): Path to the service account JSON file
**kwargs: Additional arguments to pass to the constructor
Returns:
Credentials: The constructed credentials
"""
@classmethod
def from_service_account_info(
cls,
info,
**kwargs
):
"""
Create credentials from service account info dictionary.
Args:
info (Mapping[str, str]): The service account info in JSON format
**kwargs: Additional arguments to pass to the constructor
Returns:
Credentials: The constructed credentials
"""
def with_scopes(self, scopes):
"""
Create a copy of these credentials with specified scopes.
Args:
scopes (Sequence[str]): The list of scopes to attach
Returns:
Credentials: A new credentials instance
"""
def with_quota_project(self, quota_project_id):
"""
Create a copy with a specified quota project ID.
Args:
quota_project_id (str): The project for quota and billing
Returns:
Credentials: A new credentials instance
"""Usage example:
from google.oauth2 import service_account
# From JSON file
credentials = service_account.Credentials.from_service_account_file(
'/path/to/service-account.json',
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
# From info dictionary
import json
with open('/path/to/service-account.json') as f:
info = json.load(f)
credentials = service_account.Credentials.from_service_account_info(
info,
scopes=['https://www.googleapis.com/auth/bigquery']
)
# Add quota project
credentials = credentials.with_quota_project('my-billing-project')Self-signed JWT authentication without OAuth2 flows, more efficient for service-to-service communication.
class Credentials(
google.auth.credentials.Signing,
google.auth.credentials.CredentialsWithQuotaProject
):
"""JWT-based service account credentials."""
def __init__(
self,
signer,
issuer,
subject,
audience,
additional_claims=None,
**kwargs
):
"""
Initialize JWT credentials.
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs
issuer (str): The issuer claim (typically service account email)
subject (str): The subject claim (typically service account email)
audience (str): The audience claim (typically the API endpoint)
additional_claims (Mapping[str, str]): Additional JWT claims
"""
@classmethod
def from_service_account_file(
cls,
filename,
audience,
**kwargs
):
"""
Create JWT credentials from service account file.
Args:
filename (str): Path to service account JSON file
audience (str): The STS audience which is usually the fully specified
resource name of the workload identity pool
**kwargs: Additional arguments to pass to the constructor
Returns:
Credentials: The constructed JWT credentials
"""
@classmethod
def from_service_account_info(
cls,
info,
audience,
**kwargs
):
"""
Create JWT credentials from service account info.
Args:
info (Mapping[str, str]): The service account info in JSON format
audience (str): The intended audience for the JWT
**kwargs: Additional arguments to pass to the constructor
Returns:
Credentials: The constructed JWT credentials
"""Usage example:
from google.auth import jwt
# Create JWT credentials for specific audience
credentials = jwt.Credentials.from_service_account_file(
'/path/to/service-account.json',
audience='https://example.googleapis.com/'
)
# With additional claims
credentials = jwt.Credentials.from_service_account_info(
service_account_info,
audience='https://example.googleapis.com/',
additional_claims={'custom_claim': 'value'}
)Google Distributed Cloud Hosted (GDCH) service account credentials for private cloud environments.
class ServiceAccountCredentials(google.auth.credentials.Credentials):
"""GDCH service account credentials."""
def __init__(
self,
signer,
issuer,
subject,
audience,
ca_cert_path,
token_endpoint,
**kwargs
):
"""
Initialize GDCH service account credentials.
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs
issuer (str): The issuer claim
subject (str): The subject claim
audience (str): The STS audience
ca_cert_path (str): Path to CA certificate for TLS verification
token_endpoint (str): The STS token endpoint
"""
@classmethod
def from_service_account_file(
cls,
filename,
audience,
ca_cert_path,
token_endpoint,
**kwargs
):
"""
Create GDCH credentials from service account file.
Args:
filename (str): Path to service account JSON file
audience (str): The STS audience
ca_cert_path (str): Path to CA certificate file
token_endpoint (str): The STS token endpoint
**kwargs: Additional arguments
Returns:
ServiceAccountCredentials: The constructed GDCH credentials
"""Service account JSON keys contain the following fields:
ServiceAccountInfo = TypedDict('ServiceAccountInfo', {
'type': str, # Always "service_account"
'project_id': str, # The Google Cloud project ID
'private_key_id': str, # Key ID for the private key
'private_key': str, # RSA private key in PEM format
'client_email': str, # Service account email address
'client_id': str, # Numeric client ID
'auth_uri': str, # OAuth2 authorization endpoint
'token_uri': str, # OAuth2 token endpoint
'auth_provider_x509_cert_url': str, # Provider cert URL
'client_x509_cert_url': str, # Client cert URL
'universe_domain': str # Universe domain (optional)
})class RefreshError(google.auth.exceptions.GoogleAuthError):
"""Raised when credentials cannot be refreshed."""
class MalformedError(google.auth.exceptions.GoogleAuthError):
"""Raised when credential data is malformed."""Common error scenarios:
Install with Tessl CLI
npx tessl i tessl/pypi-google-auth