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

oauth2-users.mddocs/

OAuth2 User Credentials

OAuth2 flows for user authentication including authorization code flow, refresh tokens, and user consent management. Enables applications to access Google APIs on behalf of users with their explicit consent.

Capabilities

User Access Token Credentials

OAuth2 credentials representing an authorized user, supporting automatic token refresh and scope-based access control.

class Credentials(
    google.auth.credentials.ReadOnlyScoped,
    google.auth.credentials.CredentialsWithQuotaProject
):
    """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=google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN,
        account=None,
        **kwargs
    ):
        """
        Initialize OAuth2 user credentials.
        
        Args:
            token (str): The OAuth 2.0 access token
            refresh_token (str): The optional refresh token
            id_token (str): The OpenID Connect ID Token
            token_uri (str): The token server endpoint URI
            client_id (str): The OAuth 2.0 client identifier
            client_secret (str): The OAuth 2.0 client secret
            scopes (Sequence[str]): User-defined scopes to request
            default_scopes (Sequence[str]): Default scopes passed by client libraries
            quota_project_id (str): The project for quota and billing
            expiry (datetime.datetime): The optional expiry datetime
            rapt_token (str): The optional rapt token for reauth
            refresh_handler (Callable): Custom refresh handler
            enable_reauth_refresh (bool): Whether to enable reauth refresh
            granted_scopes (Sequence[str]): The scopes that were granted
            trust_boundary (str): String representation of trust boundary meta
            universe_domain (str): The STS audience which contains the resource name
            account (str): Account identifier
        """
    
    def refresh(self, request):
        """
        Refresh the access token using the refresh token.
        
        Args:
            request (google.auth.transport.Request): HTTP transport for making requests
            
        Raises:
            google.auth.exceptions.RefreshError: If credentials cannot be refreshed
        """
    
    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 credentials

# Create credentials from OAuth2 tokens
creds = credentials.Credentials(
    token='access_token_here',
    refresh_token='refresh_token_here',
    token_uri='https://oauth2.googleapis.com/token',
    client_id='client_id_here',
    client_secret='client_secret_here'
)

# Use with scopes
creds = creds.with_scopes(['https://www.googleapis.com/auth/drive'])

# Add quota project
creds = creds.with_quota_project('my-billing-project')

User Access Token Credentials (Simple)

Simplified credentials using only an access token, useful for short-lived access without refresh capability.

class UserAccessTokenCredentials(google.auth.credentials.Credentials):
    """Credentials using only a user access token."""
    
    def __init__(self, token):
        """
        Initialize with access token.
        
        Args:
            token (str): The OAuth 2.0 access token
        """

Usage example:

from google.oauth2 import credentials

# Simple access token credentials (no refresh)
creds = credentials.UserAccessTokenCredentials(
    token='user_access_token_here'
)

ID Token Verification

Verify and decode OpenID Connect ID tokens from Google OAuth2 flows.

def verify_oauth2_token(id_token, request, audience=None, clock_skew_in_seconds=0):
    """
    Verify an ID token issued by Google's OAuth 2.0 authorization server.
    
    Args:
        id_token (Union[str, bytes]): The encoded token
        request (google.auth.transport.Request): HTTP transport for making requests
        audience (str): The expected audience of the token
        clock_skew_in_seconds (int): Acceptable clock skew in seconds
        
    Returns:
        Mapping[str, Any]: The decoded token payload
        
    Raises:
        google.auth.exceptions.GoogleAuthError: If the token is invalid
    """

def verify_token(id_token, request, audience=None, clock_skew_in_seconds=0):
    """
    Verify a token against Google's public certificates.
    
    Args:
        id_token (Union[str, bytes]): The encoded token  
        request (google.auth.transport.Request): HTTP transport for making requests
        audience (str): The expected audience
        clock_skew_in_seconds (int): Clock skew tolerance
        
    Returns:
        Mapping[str, Any]: The decoded token payload
    """

def fetch_id_token(request, audience, service_account_email=None):
    """
    Fetch an ID token from the metadata server.
    
    Args:
        request (google.auth.transport.Request): HTTP transport
        audience (str): The audience for the ID token
        service_account_email (str): Service account to impersonate
        
    Returns:
        str: The ID token
    """

Usage example:

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

# Verify ID token
request = requests.Request()
try:
    id_info = id_token.verify_oauth2_token(
        token_string, 
        request, 
        audience='your-client-id.apps.googleusercontent.com'
    )
    print(f"User ID: {id_info['sub']}")
    print(f"Email: {id_info['email']}")
except ValueError:
    print("Invalid token")

# Fetch ID token from metadata server
id_token_string = id_token.fetch_id_token(
    request, 
    'https://example.com/audience'
)

OAuth2 Client Utilities

Low-level OAuth2 client functionality for implementing custom flows.

def refresh_grant(
    request,
    token_uri,
    refresh_token,
    client_id,
    client_secret,
    scopes=None
):
    """
    Refresh an access token using a refresh token.
    
    Args:
        request (google.auth.transport.Request): HTTP transport
        token_uri (str): The OAuth 2.0 authorization server's token endpoint URI
        refresh_token (str): The refresh token
        client_id (str): The OAuth 2.0 client ID
        client_secret (str): The OAuth 2.0 client secret
        scopes (Sequence[str]): Scopes to request
        
    Returns:
        Tuple[str, Optional[str], Optional[datetime], Mapping[str, str]]:
        Access token, new refresh token, expiry, additional token response data
    """

def id_token_jwt_grant(request, token_uri, assertion):
    """
    JWT authorization grant for ID tokens.
    
    Args:
        request (google.auth.transport.Request): HTTP transport
        token_uri (str): The OAuth 2.0 authorization server's token endpoint URI  
        assertion (str): The JWT assertion
        
    Returns:
        Tuple[str, Optional[datetime], Mapping[str, str]]:
        Access token, expiry, additional token response data
    """

OAuth2 Utils

def generate_refresh_request(http_client):
    """
    Generate a request function for token refresh.
    
    Args:
        http_client: HTTP client instance
        
    Returns:
        Callable: Function that can be used to make HTTP requests
    """

def clientsecrets_to_authorized_user_info(clientsecrets_info, refresh_token):
    """
    Convert client secrets to authorized user info format.
    
    Args:
        clientsecrets_info (Mapping[str, Any]): Client secrets JSON
        refresh_token (str): The refresh token
        
    Returns:
        Mapping[str, str]: Authorized user info dictionary
    """

Error Handling

class RefreshError(google.auth.exceptions.GoogleAuthError):
    """Raised when credentials cannot be refreshed."""
    
class OAuthError(google.auth.exceptions.GoogleAuthError):
    """Raised for OAuth-specific errors."""

Common error scenarios:

  • Invalid or expired refresh token
  • Network issues during token refresh
  • Invalid client ID or client secret
  • Insufficient scopes for requested operations
  • Token format or signature validation failures

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