Google Auth Python Library

repository·main·Indexed 21 days ago

https://github.com/googleapis/google-auth-library-python

The official Google authentication library for Python, designed to simplify server-to-server authentication for Google APIs. It provides support for Application Default Credentials (ADC), Service Accounts, Impersonated Credentials, and Workload Identity Federation. The library integrates with transport layers including Requests, urllib3, and gRPC, and serves as the modern replacement for the deprecated oauth2client library.

Tokens
13.2K
Snippets
29
Records
41
Agent score
75%

What's inside google-auth

  1. Overview of the google.auth package

    main
    The google.auth package is the primary entry point for the Google Auth Python library. It provides the core functionality for discovering and managing authentication credentials used to access Google APIs. The package is organized into subpackages and submodules that handle specific authentication environments (like Compute Engine, AWS, or App Engine) and credential types (like JWT, IAM, or Impersonated Credentials).
  2. Overview of google-auth capabilities

    main

    The google-auth library is the official Google authentication library for Python. It enables authentication to Google APIs through several mechanisms and integrates with common HTTP transport libraries.

    Key features include:

    • Application Default Credentials (ADC): Support via google.auth.default.
    • Token Management: Signing and verifying JWTs (google.auth.jwt), creating Google ID Tokens, and verifying/decoding ID Tokens (google.oauth2.id_token).
    • Credential Types: Support for Service Account credentials (google.oauth2.service_account), Impersonated Credentials (google.auth.impersonated_credentials), Compute Engine credentials (google.auth.compute_engine), App Engine standard credentials (google.auth.app_engine), Identity Pool credentials (google.auth.identity_pool), and AWS credentials (google.auth.aws).
    • Security Features: Downscoping with Credential Access Boundaries (google.auth.downscoped).
    • Transport Integration: Support for Requests (google.auth.transport.requests), urllib3 (google.auth.transport.urllib3), and gRPC (google.auth.transport.grpc).

    Note: This library replaces the deprecated oauth2client library.

  3. Explore the google.oauth2 package submodules

    main

    The google.oauth2 package is the primary entry point for OAuth 2.0 authentication in this library. It provides specialized submodules for different authentication flows and credential types:

    • google.oauth2.credentials: For managing OAuth 2.0 credentials (e.g., user tokens).
    • google.oauth2.service_account: For managing Service Account credentials.
    • google.oauth2.id_token: For handling OpenID Connect ID tokens.
    • google.oauth2.sts: For Security Token Service operations.
    • google.oauth2.utils: Utility functions for the package.
    • google.oauth2._credentials_async and google.oauth2._service_account_async: Async versions of the credentials modules.
  4. Explore google.auth.transport submodules

    main

    The google.auth.transport package provides various transport implementations for handling authentication credentials across different networking libraries. Depending on your application's networking stack, you should use one of the following submodules:

    • google.auth.transport.requests: For applications using the requests library.
    • google.auth.transport.urllib3: For applications using the urllib3 library.
    • google.auth.transport._aiohttp_requests: For asynchronous applications using aiohttp.
    • google.auth.transport.grpc: For applications using gRPC.
    • google.auth.transport.mtls: For Mutual TLS (mTLS) connections.
  5. Explore the google package subpackages

    main

    The google package serves as a namespace for various Google authentication and service libraries. The primary subpackages for authentication tasks are:

    • google.auth: Contains core authentication logic, including credentials loading and service account handling.
    • google.oauth2: Provides specific implementations for OAuth 2.0 flows and credential types.
  6. Use google.auth.compute_engine for Compute Engine authentication

    main
    The google.auth.compute_engine package provides specialized authentication logic for applications running on Google Compute Engine (GCE). It is designed to automatically discover and retrieve credentials from the Compute Engine metadata server, allowing your application to authenticate with Google APIs without manually managing service account keys.
  7. Understand credential types in google.auth

    main

    The google.auth.credentials.Credentials class is used to identify an application or user to a service or API. The library supports three primary account types:

    • Service Accounts: Identifies a specific application. These are primarily used for server-to-server use cases (e.g., an application accessing a database). This library focuses heavily on service account credentials.
    • User Accounts: Obtained via user authorization (e.g., accessing a user's Google Drive files). The library provides limited support for using existing user credentials but does not provide mechanisms for obtaining them.
    • External Accounts (Workload Identity Federation): Used to identify applications running on non-Google Cloud platforms (such as AWS, Microsoft Azure, or any OIDC-compliant identity provider) or via X.509 certificates.
  8. Downscope credentials with Credential Access Boundaries

    main

    Downscoping restricts the IAM permissions of a short-lived credential using a Credential Access Boundary. This is primarily used to implement the Principle of Least Privilege, especially when passing tokens to consumers.

    Note: Currently, only Cloud Storage supports Credential Access Boundaries. Other Google Cloud services do not support this feature.

    Workflow

    1. Token Broker: Defines AvailabilityCondition and AccessBoundaryRule to create a CredentialAccessBoundary. It then generates downscoped credentials from a source credential.
    2. Token Consumer: Receives the downscoped token and expiry, then uses them to initialize a client (e.g., google.cloud.storage.Client).
    import google.auth
    from google.auth import downscoped
    from google.auth.transport import requests
    
    # 1. Define the boundary
    available_resource = '//storage.googleapis.com/projects/_/buckets/bucket-123'
    available_permissions = ['inRole:roles/storage.objectViewer']
    availability_expression = "resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')"
    
    availability_condition = downscoped.AvailabilityCondition(availability_expression)
    rule = downscoped.AccessBoundaryRule(
        available_resource=available_resource,
        available_permissions=available_permissions,
        availability_condition=availability_condition
    )
    credential_access_boundary = downscoped.CredentialAccessBoundary(rules=[rule])
    
    # 2. Create downscoped credentials from source
    source_credentials, _ = google.auth.default()
    downscoped_credentials = downscoped.Credentials(
        source_credentials=source_credentials,
        credential_access_boundary=credential_access_boundary
    )
    
    # 3. Refresh to get the token
    downscoped_credentials.refresh(requests.Request())
    
    # Values to pass to consumer
    access_token = downscoped_credentials.token
    expiry = downscoped_credentials.expiry
  9. Explore google.auth subpackages and submodules

    main

    The google.auth library is modular. Depending on your environment and authentication requirements, you may need to interact with specific sub-components:

    Subpackages

    • google.auth.compute_engine: Authentication for Google Compute Engine environments.
    • google.auth.crypt: Cryptographic utilities.
    • google.auth.transport: Transport-related authentication logic.

    Key Submodules

    • Environment & Cloud Providers: google.auth.app_engine, google.auth.aws, google.auth.external_account, google.auth.identity_pool.
    • Credential Management: google.auth.credentials, google.auth.impersonated_credentials, google.auth.downscoped, google.auth.iam.
    • Token & Identity Formats: google.auth.jwt, google.auth.jwt (and async variants).
    • Error Handling: google.auth.exceptions.
  10. Access Google Cloud via Workload Identity Federation

    main

    Workload Identity Federation allows applications running outside of Google Cloud (e.g., AWS, Azure, or OIDC providers) to impersonate a Google service account without needing to manage long-lived service account private keys.

    Instead of a service account key file, you use a credential configuration file containing non-sensitive metadata. This file instructs the library on how to retrieve external subject tokens and exchange them for Google access tokens.

    Supported Providers

    • AWS: Requires a workload identity pool, AWS added as an identity provider, and permission to impersonate a service account. If using IDMSv2, add "imdsv2_session_token_url": "http://169.254.169.254/latest/api/token" to the credential_source section of the configuration.
    • Microsoft Azure: Requires a workload identity pool, Azure added as an identity provider, and Azure tenant configuration for federation.
    • OIDC Identity Providers: Supports two modes:
      • File-sourced: A background process continuously refreshes a local file (plain text or JSON) with a new OIDC token.
      • URL-sourced: A local server hosts a GET endpoint that returns the OIDC token (plain text or JSON).
  11. Migrate from oauth2client to google-auth

    main

    The oauth2client library is deprecated and is being replaced by google-auth. google-auth is designed to be a modern, secure, and transport-agnostic replacement focused on Google-specific authentication (especially service account use cases).

    Key Differences and Migration Notes

    • Transports: Unlike oauth2client which was tied to httplib2, google-auth supports urllib3, requests, and gRPC. It also provides legacy support for httplib2 via the google-auth-httplib2 package to assist with gradual migrations.
    • Scope Reduction: google-auth has a more focused scope. Some features from oauth2client are moved to specialized libraries:
      • User Credentials (3-party OAuth 2.0 flow): Use google-auth-oauthlib instead of the core google-auth library.
      • Credential Storage: The core library does not provide built-in credential storage; applications should provide their own storage implementation or use google-auth-oauthlib for related functionality.
    • Compatibility: The google-api-python-client library supports both oauth2client and google-auth, allowing you to switch libraries without breaking your API client integration.