Google Authentication Library providing comprehensive authentication mechanisms for Google APIs and services including OAuth 2.0, JWT, and service account credentials
npx @tessl/cli install tessl/pypi-google-auth@2.40.0A comprehensive Python library for authenticating to Google APIs and services. Provides server-to-server authentication mechanisms including OAuth 2.0, JWT, and service account credentials with built-in token management, automatic refresh capabilities, and secure credential storage. Designed for high reusability across Google Cloud applications, client libraries, and any Python application requiring authentication with Google services.
pip install google-authimport google.auth
from google.auth import credentials
from google.oauth2 import service_accountFor specific credential types:
from google.auth import default
from google.oauth2 import credentials as oauth2_credentials
from google.auth import jwt
from google.auth.transport import requestsimport google.auth
from google.auth.transport import requests
# Use Application Default Credentials
credentials, project = google.auth.default(
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
# Create an authenticated HTTP session
authed_session = requests.AuthorizedSession(credentials)
# Make authenticated requests
response = authed_session.get('https://www.googleapis.com/compute/v1/projects')The library follows a modular design with clear separation of concerns:
google.auth.credentials)google.oauth2.*)google.auth.transport.*)google.auth.crypt, google.auth.jwt)google.auth.aio.*)This design enables flexible authentication across different environments while maintaining consistent interfaces for credential management and token handling.
Automatically detects and loads the most appropriate credentials for the current environment, following Google Cloud's standard credential discovery flow.
def default(
scopes=None,
request=None,
quota_project_id=None,
default_scopes=None
):
"""
Construct credentials from Application Default Credentials.
Args:
scopes (Sequence[str]): The list of scopes for the credentials
request (google.auth.transport.Request): HTTP transport for credential refresh
quota_project_id (str): Project for quota and billing
default_scopes (Sequence[str]): Default scopes from client library
Returns:
Tuple[google.auth.credentials.Credentials, Optional[str]]:
The constructed credentials and project ID
"""
def load_credentials_from_file(
filename,
scopes=None,
default_scopes=None,
quota_project_id=None,
request=None
):
"""
Load Google credentials from a file.
Args:
filename (str): Path to credentials file
scopes (Sequence[str]): Scopes for the credentials
default_scopes (Sequence[str]): Default scopes from client library
quota_project_id (str): Project for quota and billing
request (google.auth.transport.Request): HTTP transport
Returns:
Tuple[google.auth.credentials.Credentials, Optional[str]]:
Loaded credentials and project ID
"""
def load_credentials_from_dict(
info,
scopes=None,
default_scopes=None,
quota_project_id=None,
request=None
):
"""
Load Google credentials from a dictionary.
Args:
info (Mapping[str, str]): Credential information dictionary
scopes (Sequence[str]): Scopes for the credentials
default_scopes (Sequence[str]): Default scopes from client library
quota_project_id (str): Project for quota and billing
request (google.auth.transport.Request): HTTP transport
Returns:
Tuple[google.auth.credentials.Credentials, Optional[str]]:
Loaded credentials and project ID
"""Application Default Credentials
Server-to-server authentication using service account keys and JWT tokens, supporting both OAuth2 flows and self-signed JWTs.
class Credentials(google.auth.credentials.Scoped):
"""Service account credentials for server-to-server 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=credentials.DEFAULT_UNIVERSE_DOMAIN,
trust_boundary=None,
**kwargs
): ...
@classmethod
def from_service_account_file(
cls,
filename,
**kwargs
): ...
@classmethod
def from_service_account_info(
cls,
info,
**kwargs
): ...OAuth2 flows for user authentication including authorization code flow, refresh tokens, and user consent management.
class Credentials(google.auth.credentials.ReadOnlyScoped):
"""OAuth2 credentials for user authentication."""
def __init__(
self,
token,
refresh_token=None,
id_token=None,
token_uri=None,
client_id=None,
client_secret=None,
scopes=None,
default_scopes=None,
quota_project_id=None,
expiry=None,
rapt_token=None,
refresh_handler=None,
enable_reauth_refresh=False,
granted_scopes=None,
trust_boundary=None,
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
account=None,
**kwargs
): ...JSON Web Token-based authentication for service-to-service communication without OAuth2 flows.
class Credentials(
google.auth.credentials.Signing,
google.auth.credentials.CredentialsWithQuotaProject
):
"""JWT-based credentials for service authentication."""
def __init__(
self,
signer,
issuer,
subject,
audience,
additional_claims=None,
**kwargs
): ...
def encode(signer, payload, header=None, key_id=None):
"""
Encode a JWT token.
Args:
signer (google.auth.crypt.Signer): The signer used to sign the JWT
payload (Mapping[str, str]): JWT payload claims
header (Mapping[str, str]): Additional JWT header fields
key_id (str): Key ID to add to JWT header (overrides signer key_id)
Returns:
bytes: Encoded JWT token
"""
def decode(token, certs=None, verify=True, audience=None, clock_skew_in_seconds=0):
"""
Decode and verify a JWT token.
Args:
token (str): The encoded JWT
certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): Certificate used to validate JWT signature
verify (bool): Whether to perform signature and claim validation
audience (Union[str, list]): The audience claim that this JWT should contain
clock_skew_in_seconds (int): The number of seconds of clock skew to tolerate
Returns:
Mapping[str, str]: Decoded JWT payload
"""HTTP transport implementations for making authenticated requests across different HTTP libraries.
class Request(google.auth.transport.Request):
"""Requests-based HTTP transport."""
def __init__(self, session=None): ...
class AuthorizedSession(requests.Session):
"""Requests session with automatic credential refresh."""
def __init__(self, credentials, **kwargs): ...Workload identity and external identity provider integration for multi-cloud and hybrid scenarios.
class Credentials(google.auth.credentials.Scoped):
"""External account credentials for workload identity."""
def __init__(
self,
audience,
subject_token_type,
token_url,
**kwargs
): ...Token signing and verification utilities supporting RSA and ECDSA algorithms.
class RSASigner(google.auth.crypt.Signer):
"""RSA-based token signer."""
def __init__(self, key): ...
def sign(self, message): ...
class ES256Signer(google.auth.crypt.Signer):
"""ECDSA P-256 token signer."""
def __init__(self, key): ...
def sign(self, message): ...Full async implementations using aiohttp for non-blocking authentication flows.
class Request(google.auth.transport.Request):
"""Async HTTP transport using aiohttp."""
def __init__(self, session=None): ...
async def __call__(self, *args, **kwargs): ...
class AuthorizedSession(aiohttp.ClientSession):
"""Async session with automatic credential refresh."""
def __init__(self, credentials, **kwargs): ...class TokenState(enum.Enum):
"""Token freshness states."""
FRESH = 1
STALE = 2
INVALID = 3
class Credentials:
"""Base credentials interface."""
token: Optional[str]
expiry: Optional[datetime.datetime]
@property
def token_state(self) -> TokenState: ...
@property
def valid(self) -> bool: ...
@property
def expired(self) -> bool: ...
def refresh(self, request: Request) -> None: ...
class Scoped:
"""Interface for credentials supporting OAuth2 scopes."""
def with_scopes(self, scopes: Sequence[str]) -> 'Credentials': ...
class CredentialsWithQuotaProject:
"""Interface for credentials with quota project support."""
def with_quota_project(self, quota_project_id: str) -> 'Credentials': ...
Request = Callable[[str, str, Optional[bytes], Optional[Mapping[str, str]]], Any]