CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-google-auth

Google Authentication Library providing comprehensive authentication mechanisms for Google APIs and services including OAuth 2.0, JWT, and service account credentials

Pending
Overview
Eval results
Files

jwt.mddocs/

JWT Credentials

JSON Web Token-based authentication for service-to-service communication without OAuth2 flows. JWT credentials provide efficient authentication by creating self-signed tokens that can be verified without server-side validation.

Capabilities

JWT Credentials

Self-signed JWT authentication for direct API access without OAuth2 token exchange.

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
    ):
        """
        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 intended audience for the JWT
            **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]): 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
        """
    
    def with_claims(self, issuer=None, subject=None, audience=None, **additional_claims):
        """
        Create a copy with modified claims.
        
        Args:
            issuer (str): The issuer claim
            subject (str): The subject claim
            audience (str): The audience claim
            **additional_claims: Additional claims to include
            
        Returns:
            Credentials: A new JWT credentials instance
        """

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', 'scope': 'read'}
)

# Modify claims
credentials = credentials.with_claims(
    audience='https://different.googleapis.com/',
    role='admin'
)

On-Demand JWT Credentials

JWT credentials that generate tokens on-demand rather than pre-generating them, useful for dynamic claim generation.

class OnDemandCredentials(google.auth.credentials.Credentials):
    """On-demand JWT credentials that generate tokens when needed."""
    
    def __init__(
        self,
        signer,
        issuer,
        subject,
        audience,
        additional_claims=None,
        **kwargs
    ):
        """
        Initialize on-demand JWT 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 audience claim
            additional_claims (Mapping[str, str]): Additional JWT claims
        """
    
    @classmethod
    def from_service_account_file(
        cls,
        filename,
        audience,
        **kwargs
    ):
        """
        Create on-demand JWT credentials from service account file.
        
        Args:
            filename (str): Path to service account JSON file
            audience (str): The intended audience for the JWT
            **kwargs: Additional arguments
            
        Returns:
            OnDemandCredentials: The constructed credentials
        """

JWT Token Operations

Low-level JWT encoding and decoding utilities for custom JWT implementations.

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, Any]): The 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: The encoded JWT token
        
    Raises:
        ValueError: If the signer or payload is invalid
    """

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
        
    Raises:
        ValueError: If the token is invalid or verification fails
    """

def decode_header(token):
    """
    Decode JWT header without verification.
    
    Args:
        token (Union[str, bytes]): The JWT token
        
    Returns:
        Mapping[str, str]: The JWT header
    """

Usage example:

from google.auth import jwt
import json

# Load service account key
with open('/path/to/service-account.json') as f:
    key_data = json.load(f)

private_key = key_data['private_key']
service_account_email = key_data['client_email']

# Create signer from private key
from google.auth import crypt
signer = crypt.RSASigner.from_string(private_key, key_id='key-1')

# Create JWT payload
import time
now = int(time.time())
payload = {
    'iss': service_account_email,
    'sub': service_account_email,
    'aud': 'https://example.googleapis.com/',
    'iat': now,
    'exp': now + 3600,  # 1 hour expiry
    'custom_claim': 'value'
}

# Encode JWT
token = jwt.encode(signer, payload)
print(f"JWT: {token.decode('utf-8')}")

# Decode JWT (for verification)
public_key = get_public_key()  # Get corresponding public key
decoded_payload = jwt.decode(
    token, 
    public_key, 
    audience='https://example.googleapis.com/'
)
print(f"Decoded: {decoded_payload}")

JWT Async Support

Async versions of JWT credentials for non-blocking token generation.

class Credentials(google.auth.credentials.Credentials):
    """Async JWT credentials."""
    
    async def refresh(self, request):
        """
        Async refresh of JWT token.
        
        Args:
            request (google.auth.transport.Request): Async HTTP transport
        """

JWT Claims

Standard and custom JWT claims supported by Google Auth:

JWTClaims = TypedDict('JWTClaims', {
    'iss': str,      # Issuer (service account email)
    'sub': str,      # Subject (service account email) 
    'aud': str,      # Audience (API endpoint)
    'iat': int,      # Issued at time (Unix timestamp)
    'exp': int,      # Expiration time (Unix timestamp)
    'scope': str,    # Space-delimited scopes (optional)
    'target_audience': str,  # Target audience for ID tokens (optional)
}, total=False)

Error Handling

class MalformedError(google.auth.exceptions.GoogleAuthError):
    """Raised when JWT data is malformed."""
    
class RefreshError(google.auth.exceptions.GoogleAuthError):
    """Raised when JWT refresh fails."""

Common JWT error scenarios:

  • Invalid or malformed JWT structure
  • JWT signature verification failures
  • Expired JWT tokens
  • Invalid audience or issuer claims
  • Missing required claims (iss, sub, aud, exp)
  • Unsupported JWT algorithms
  • Invalid private key format for signing

Install with Tessl CLI

npx tessl i tessl/pypi-google-auth

docs

adc.md

async.md

crypt.md

external-accounts.md

index.md

jwt.md

oauth2-users.md

service-accounts.md

transport.md

tile.json