### Initialize gRPC Stub and Execute Request Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Demonstrates how to use an established gRPC channel to initialize a service-specific stub and perform a remote procedure call. This example specifically targets the Pub/Sub ListTopics method. ```python from google.pubsub.v1 import pubsub_pb2 pubsub = pubsub_pb2.PublisherStub(channel) response = pubsub.ListTopics( pubsub_pb2.ListTopicsRequest(project='your-project')) ``` -------------------------------- ### Install Google Auth with urllib3 Extras Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/transport/urllib3.html This code snippet demonstrates how to install the google-auth library with the necessary extras for urllib3 network transport. It's crucial for enabling specific network functionalities within the library. The installation command should be run within your virtual environment. ```bash pip install google-auth[urllib3] ``` -------------------------------- ### Generate Identity Tokens Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Provides examples for generating OpenID Connect identity tokens using Service Account files and Compute Engine metadata. ```python # Service Account from google.oauth2 import service_account target_audience = 'https://example.com' creds = service_account.IDTokenCredentials.from_service_account_file( '/path/to/svc.json', target_audience=target_audience) # Compute Engine from google.auth import compute_engine import google.auth.transport.requests request = google.auth.transport.requests.Request() creds = compute_engine.IDTokenCredentials(request, target_audience=target_audience) ``` -------------------------------- ### Install google-auth using pip Source: https://googleapis.dev/python/google-auth/latest/index.html This command installs or upgrades the google-auth library using pip. Ensure you have Python and pip installed in your environment. ```shell $ pip install --upgrade google-auth ``` -------------------------------- ### Install google-auth via pip Source: https://googleapis.dev/python/google-auth/latest/_sources/index.rst.txt The standard method for installing the google-auth library in a Python environment using the pip package manager. ```bash pip install --upgrade google-auth ``` -------------------------------- ### Generate ID Tokens from Credentials Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Demonstrates how to create IDTokenCredentials from existing credentials and how to fetch an ID token from the current running environment using google.oauth2.id_token. ```python from google.oauth2 import impersonated_credentials import google.oauth2.id_token import google.auth.transport.requests target_audience = 'https://example.com' creds = impersonated_credentials.IDTokenCredentials(target_credentials, target_audience=target_audience) request = google.auth.transport.requests.Request() id_token = google.oauth2.id_token.fetch_id_token(request, "https://pubsub.googleapis.com") ``` -------------------------------- ### Initialize Async Transport Module Imports Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/transport/_aiohttp_requests.html This snippet demonstrates the necessary imports and module setup for the experimental aiohttp-based transport adapter. It includes dependencies for asynchronous operations, logging, and Google Auth core utilities. ```python import asyncio import functools import logging import aiohttp import urllib3 from google.auth import _helpers from google.auth import exceptions from google.auth import transport from google.auth.aio import _helpers as _helpers_async from google.auth.transport import requests _LOGGER = logging.getLogger(__name__) ``` -------------------------------- ### Create Downscoped Credentials with Access Boundaries Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Shows how to initialize downscoped credentials using a credential access boundary to limit access to specific GCS resources. ```python downscoped_credentials = downscoped.Credentials( source_credentials=source_credentials, credential_access_boundary=credential_access_boundary) storage_client = storage.Client(project='my_project_id', credentials=downscoped_credentials) bucket = storage_client.bucket('bucket-123') blob = bucket.blob('customer-a-data.txt') print(blob.download_as_string()) ``` -------------------------------- ### Generate X.509 Credential Configuration Files Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Uses the gcloud CLI to create credential and certificate configuration files for X.509 certificate-sourced credentials. Supports both default and custom file locations for certificate configurations. ```bash gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-cert-path "$PATH_TO_CERTIFICATE" \ --credential-cert-private-key-path "$PATH_TO_PRIVATE_KEY" \ --credential-cert-trust-chain-path "$PATH_TO_TRUST_CHAIN" \ --output-file /path/to/config.json ``` ```bash gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-cert-path "$PATH_TO_CERTIFICATE" \ --credential-cert-private-key-path "$PATH_TO_PRIVATE_KEY" \ --credential-cert-trust-chain-path "$PATH_TO_TRUST_CHAIN" \ --credential-cert-configuration-output-file "/custom/path/cert_config.json" \ --output-file /path/to/config.json ``` -------------------------------- ### Instantiate OAuth 2.0 Credentials in Python Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Demonstrates how to create a Credentials object using an access token, or a combination of access and refresh tokens for automatic token renewal. These objects are used to authenticate requests to Google APIs. ```python import google.oauth2.credentials # Basic initialization credentials = google.oauth2.credentials.Credentials('access_token') # Initialization with refresh capabilities credentials = google.oauth2.credentials.Credentials( 'access_token', refresh_token='refresh_token', token_uri='token_uri', client_id='client_id', client_secret='client_secret') ``` -------------------------------- ### Refresh and Consume Downscoped Credentials Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Demonstrates how to refresh downscoped credentials and use them within a token consumer pattern to access Google Cloud Storage with restricted permissions. ```python downscoped_credentials.refresh(requests.Request()) access_token = downscoped_credentials.token expiry = downscoped_credentials.expiry import google.oauth2 from google.auth.transport import requests from google.cloud import storage downscoped_token, expiry = get_token_from_broker( requests.Request(), scopes=['https://www.googleapis.com/auth/cloud-platform']) credentials = google.oauth2.credentials.Credentials( downscoped_token, expiry=expiry, scopes=['https://www.googleapis.com/auth/cloud-platform'], refresh_handler=get_token_from_broker) storage_client = storage.Client(project='my_project_id', credentials=credentials) bucket = storage_client.bucket('bucket-123') blob = bucket.blob('customer-a-data.txt') print(blob.download_as_bytes().decode("utf-8")) ``` -------------------------------- ### Generate Workforce Pool Credential Configuration via CLI Source: https://googleapis.dev/python/google-auth/latest/user-guide.html This command creates a configuration file required for executable-sourced credentials. It requires parameters for workforce pool identification, subject token type, and the absolute path to the executable command. ```bash gcloud iam workforce-pools create-cred-config \ locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ --subject-token-type=$SUBJECT_TOKEN_TYPE \ --executable-command=$EXECUTABLE_COMMAND \ --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ --output-file /path/to/generated/config.json ``` -------------------------------- ### Perform Authenticated Requests with Transports Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Provides examples of making authenticated HTTP and gRPC requests using AuthorizedSession, AuthorizedHttp, and secure_authorized_channel. ```python # Requests transport from google.auth.transport.requests import AuthorizedSession authed_session = AuthorizedSession(credentials) response = authed_session.get('https://www.googleapis.com/storage/v1/b') # urllib3 transport from google.auth.transport.urllib3 import AuthorizedHttp authed_http = AuthorizedHttp(credentials) response = authed_http.request('GET', 'https://www.googleapis.com/storage/v1/b') # gRPC transport import google.auth.transport.grpc http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(credentials, http_request, 'pubsub.googleapis.com:443') ``` -------------------------------- ### Initialize Service Account Credentials in Python Source: https://googleapis.dev/python/google-auth/latest/reference/google.oauth2.service_account.html Demonstrates how to create service account credentials using a JSON file path or a loaded dictionary. These methods are the standard way to authenticate service accounts in Google Cloud applications. ```python from google.oauth2 import service_account import json # Initialize from file credentials = service_account.Credentials.from_service_account_file('service-account.json') # Initialize from dictionary service_account_info = json.load(open('service-account.json')) credentials = service_account.Credentials.from_service_account_info(service_account_info) ``` -------------------------------- ### Initialize Service Account Credentials in Python Source: https://googleapis.dev/python/google-auth/latest/reference/google.oauth2._service_account_async.html Demonstrates how to create asynchronous service account credentials using a JSON key file or a loaded dictionary. These methods support optional parameters like scopes and subject delegation. ```python import json from google.oauth2 import service_account_async # Create from file credentials = service_account_async.Credentials.from_service_account_file('service-account.json') # Create from dictionary service_account_info = json.load(open('service-account.json')) credentials = service_account_async.Credentials.from_service_account_info(service_account_info) # Create with additional scopes and subject credentials = service_account_async.Credentials.from_service_account_file( 'service-account.json', scopes=['email'], subject='user@example.com' ) ``` -------------------------------- ### Establish Authenticated gRPC Channel Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Configures a secure gRPC channel by combining metadata-based authorization credentials with SSL channel credentials. This setup is required for making authenticated requests to Google Cloud gRPC services. ```python google_auth_credentials = grpc.metadata_call_credentials(metadata_plugin) ssl_credentials = grpc.ssl_channel_credentials() composite_credentials = grpc.composite_channel_credentials( ssl_credentials, google_auth_credentials) channel = grpc.secure_channel( 'pubsub.googleapis.com:443', composite_credentials) ``` -------------------------------- ### Create Credentials with Modified Quota Project (Python) Source: https://googleapis.dev/python/google-auth/latest/reference/google.oauth2.service_account.html Demonstrates creating a copy of existing credentials with an updated quota project ID. The `with_quota_project()` method allows for specifying a different project for quota and billing purposes without altering the original credentials object. ```python from google.auth import service_account # Assuming 'credentials' is an existing IDTokenCredentials object quota_project_id = 'my-new-project-id' updated_credentials = credentials.with_quota_project(quota_project_id) ``` -------------------------------- ### Get Application Default Credentials (Python) Source: https://googleapis.dev/python/google-auth/latest/_sources/user-guide.rst.txt Obtains Google Application Default Credentials (ADC) which abstract authentication across Google Cloud environments. This function can automatically detect credentials when running on Google Cloud or locally with the Google Cloud SDK installed. It can also accept specific scopes for more granular access. ```python import google.auth credentials, project = google.auth.default() # With specific scopes: credentials, project = google.auth.default( scopes=['https://www.googleapis.com/auth/cloud-platform']) ``` -------------------------------- ### Configure Domain-wide Delegation and Scopes in Python Source: https://googleapis.dev/python/google-auth/latest/reference/google.oauth2.service_account.html Shows how to apply specific scopes and user subjects for domain-wide delegation during credential initialization. It also demonstrates how to modify existing credentials using immutable pattern methods. ```python # Initialize with specific scopes and subject credentials = service_account.Credentials.from_service_account_file( 'service-account.json', scopes=['email'], subject='user@example.com') # Modify existing credentials scoped_credentials = credentials.with_scopes(['email']) delegated_credentials = credentials.with_subject('user@example.com') credentials = credentials.with_quota_project('myproject-123') ``` -------------------------------- ### get Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.transport.requests.html Sends a GET request to the specified URL. ```APIDOC ## GET /get ### Description Sends a GET request. Returns a `Response` object. ### Method GET ### Endpoint /get ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (str) - URL for the new `Request` object. - ****kwargs** - Optional arguments that `request` takes. ### Request Example ```python response = authed_session.get('https://example.com/data') ``` ### Response #### Success Response (200) - **response** (requests.Response) - The Response object from the server. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Initialize OAuth 2.0 Credentials Source: https://googleapis.dev/python/google-auth/latest/_modules/google/oauth2/credentials.html Demonstrates the initialization of the Credentials class, which manages OAuth 2.0 tokens and refresh logic. It supports optional parameters like quota project IDs, reauth flags, and custom refresh handlers. ```python from google.oauth2 import credentials # Example of creating credentials with a quota project credentials = credentials.Credentials( token="ya29.example", refresh_token="1//example", token_uri="https://oauth2.googleapis.com/token", client_id="client-id", client_secret="client-secret" ) # Modifying the quota project credentials = credentials.with_quota_project('myproject-123') ``` -------------------------------- ### Implement Custom Subject Token Supplier in Python Source: https://googleapis.dev/python/google-auth/latest/user-guide.html This Python code demonstrates how to create a custom `SubjectTokenSupplier` by extending `google.auth.identity_pool.SubjectTokenSupplier`. The `get_subject_token` method should attempt to retrieve a valid OIDC or SAML subject token for the given audience and token type. If an error occurs, it should raise a `google.auth.exceptions.RefreshError`, specifying whether the operation is retryable. The example also shows how to instantiate `identity_pool.Credentials` with the custom supplier. ```python from google.auth import exceptions from google.auth import identity_pool class CustomSubjectTokenSupplier(identity_pool.SubjectTokenSupplier): def get_subject_token(self, context, request): audience = context.audience subject_token_type = context.subject_token_type try: # Attempt to return the valid subject token of the requested type for the requested audience. # Replace this with your actual token retrieval logic. pass except Exception as e: # If token retrieval fails, raise a refresh error, setting retryable to true if the client should # attempt to retrieve the subject token again. raise exceptions.RefreshError(str(e), retryable=True) # Example usage: # AUDIENCE = "//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID" # SCOPES = ["https://www.googleapis.com/auth/cloud-platform"] # USER_PROJECT = "your-workforce-pool-user-project" # supplier = CustomSubjectTokenSupplier() # credentials = identity_pool.Credentials( # AUDIENCE, # Set GCP Audience. # "urn:ietf:params:aws:token-type:jwt", # Set subject token type. # subject_token_supplier=supplier, # Set supplier. # scopes=SCOPES, # Set desired scopes. # workforce_pool_user_project=USER_PROJECT # Set workforce pool user project. # ) ``` -------------------------------- ### POST /from_service_account_file Source: https://googleapis.dev/python/google-auth/latest/reference/google.oauth2._service_account_async.html Initializes credentials from a local service account JSON file. ```APIDOC ## POST /from_service_account_file ### Description Creates a credentials instance from a service account JSON file. ### Method POST ### Endpoint /from_service_account_file ### Parameters #### Request Body - **filename** (str) - Required - The path to the service account json file. - **kwargs** (dict) - Optional - Additional arguments such as scopes or subject. ### Response #### Success Response (200) - **credentials** (IDTokenCredentials) - The initialized credentials instance. ``` -------------------------------- ### GET /request_encode_url Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.transport.urllib3.html Encodes data into the URL itself. This is useful for request methods like GET, HEAD, DELETE, etc., where the body is not typically used for parameters. ```APIDOC ## GET /request_encode_url ### Description Makes a request using `urlopen()` with the `fields` encoded in the URL. This method is useful for request methods like GET, HEAD, DELETE, etc., where parameters are appended to the URL. ### Method GET ### Endpoint `/request_encode_url` ### Parameters #### Query Parameters - **method** (string) - Required - The HTTP request method (e.g., GET, POST). - **url** (string) - Required - The URL to perform the request on. - **fields** (object) - Optional - Data to encode and send in the URL. Typically key-value pairs. - **headers** (object) - Optional - A dictionary of custom headers to send. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. ### Request Example ```json { "method": "GET", "url": "https://example.com/search", "fields": { "query": "google auth", "limit": 10 } } ``` ### Response #### Success Response (200) - **response** (object) - The HTTP response object from `urlopen()`. #### Response Example ```json { "response": "" } ``` ``` -------------------------------- ### Configure mTLS with OpenSSL in Python Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/transport/urllib3.html Demonstrates how to manually configure an SSL context with client certificates and private keys using pyOpenSSL and urllib3 for mutual TLS authentication. ```python from OpenSSL import crypto import urllib3.contrib.pyopenssl import certifi urllib3.contrib.pyopenssl.inject_into_urllib3() ctx = urllib3.util.ssl_.create_urllib3_context() ctx.load_verify_locations(cafile=certifi.where()) pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert) ctx._ctx.use_certificate(x509) ctx._ctx.use_privatekey(pkey) http = urllib3.PoolManager(ssl_context=ctx) ``` -------------------------------- ### Send GET Request with Google Auth Python Session Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.transport.requests.html Shows how to send a GET request using an authenticated session object. This method is a wrapper around the underlying `requests.Session.request` method and can accept various optional arguments. ```python response = authed_session.get(url, **kwargs) ``` -------------------------------- ### GET /get_cred_info Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.credentials.html Retrieves the credential information as a JSON mapping. ```APIDOC ## GET /get_cred_info ### Description Returns the credential information JSON, which is used by client libraries for error messaging. ### Method GET ### Response #### Success Response (200) - **credential_info** (Mapping) - A dictionary containing credential metadata. ``` -------------------------------- ### Create JWT Credentials Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/_jwt_async.html Shows how to initialize JWT credentials using service account files or direct signer instances. These credentials are used for authenticating requests with an audience claim. ```python import json from google.auth import jwt_async audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher' # From file credentials = jwt_async.Credentials.from_service_account_file( 'service-account.json', audience=audience) # From parsed info service_account_info = json.load(open('service-account.json')) credentials = jwt_async.Credentials.from_service_account_info( service_account_info, audience=audience) ``` -------------------------------- ### Create Credentials with Universe Domain (Python) Source: https://googleapis.dev/python/google-auth/latest/reference/google.oauth2._service_account_async.html Demonstrates how to create a new credentials instance with a modified universe domain. The `with_universe_domain` method returns a new credential object, leaving the original unchanged. This is useful for targeting different Google Cloud environments or regions. ```python from google.auth.credentials import Credentials # Assuming 'credentials' is an existing Credentials instance # new_credentials = credentials.with_universe_domain('my-universe.com') ``` -------------------------------- ### default_client_cert_source Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.transport.mtls.html Gets a callback which returns the default client SSL credentials. ```APIDOC ## default_client_cert_source() ### Description Get a callback which returns the default client SSL credentials. ### Returns - Callable, bytes: A callback which returns the default client certificate bytes and private key bytes, both in PEM format. ### Return type `Callable`, `bytes``bytes` ### Raises - google.auth.exceptions.DefaultClientCertSourceError: If the default client SSL credentials don’t exist or are malformed. ``` -------------------------------- ### default_client_encrypted_cert_source Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.transport.mtls.html Gets a callback which returns the default encrypted client SSL credentials. ```APIDOC ## default_client_encrypted_cert_source(_cert_path_, _key_path_) ### Description Get a callback which returns the default encrpyted client SSL credentials. ### Parameters #### Path Parameters - **cert_path** (str) - Required - The cert file path. The default client certificate will be written to this file when the returned callback is called. - **key_path** (str) - Required - The key file path. The default encrypted client key will be written to this file when the returned callback is called. ### Returns - Callable, str, bytes: A callback which generates the default client certificate, encrpyted private key and passphrase. It writes the certificate and private key into the cert_path and key_path, and returns the cert_path, key_path and passphrase bytes. ### Return type `Callable`, `str``str``bytes` ### Raises - google.auth.exceptions.DefaultClientCertSourceError: If any problem occurs when loading or saving the client certificate and key. ``` -------------------------------- ### Manage Access Boundary Rule Properties and Validation Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/downscoped.html This snippet demonstrates the implementation of properties for resource management, including type checking and validation for permissions and availability conditions. It ensures that inputs conform to the expected formats required for downscoped credential generation. ```python @property def available_resource(self): return self._available_resource @available_resource.setter def available_resource(self, value): if not isinstance(value, str): raise exceptions.InvalidType("The provided available_resource is not a string.") self._available_resource = value @property def available_permissions(self): return tuple(self._available_permissions) @available_permissions.setter def available_permissions(self, value): for available_permission in value: if not isinstance(available_permission, str): raise exceptions.InvalidType("Provided available_permissions are not a list of strings.") if available_permission.find("inRole:") != 0: raise exceptions.InvalidValue("available_permissions must be prefixed with 'inRole:'.") self._available_permissions = list(value) ``` -------------------------------- ### GET /credentials/scopes Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth._credentials_async.html Check and manage OAuth 2.0 scopes for credentials that implement the Scoped interface. ```APIDOC ## GET /credentials/scopes ### Description Checks if the current credentials possess the required OAuth 2.0 scopes. ### Method GET ### Endpoint /credentials/scopes ### Parameters #### Query Parameters - **scopes** (array of strings) - Required - The list of scopes to verify. ### Request Example GET /credentials/scopes?scopes=["https://www.googleapis.com/auth/cloud-platform"] ### Response #### Success Response (200) - **has_scopes** (boolean) - Returns true if the credentials contain all requested scopes. #### Response Example { "has_scopes": true } ``` -------------------------------- ### Get Universe Domain Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.aws.html This property returns the universe domain value associated with the credentials. ```python @property def _universe_domain(self) -> str: """ The universe domain value. """ pass ``` -------------------------------- ### Create Credentials from Authorized User JSON File (Python) Source: https://googleapis.dev/python/google-auth/latest/_modules/google/oauth2/credentials.html This class method simplifies the creation of Credentials from a JSON file. It reads the JSON file, parses its content, and then utilizes the from_authorized_user_info method to construct the Credentials object. This is useful for loading pre-configured credentials from storage. ```python @classmethod def from_authorized_user_file(cls, filename, scopes=None): """Creates a Credentials instance from an authorized user json file. Args: filename (str): The path to the authorized user json file. scopes (Sequence[str]): Optional list of scopes to include in the credentials. Returns: google.oauth2.credentials.Credentials: The constructed credentials. Raises: ValueError: If the file is not in the expected format. """ with io.open(filename, "r", encoding="utf-8") as json_file: data = json.load(json_file) return cls.from_authorized_user_info(data, scopes) ``` -------------------------------- ### Get Token State Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.aws.html This property returns the current state of the token, referring to the TokenState enum. ```python @property def _token_state(self) -> TokenState: """ See :obj:`TokenState` """ pass ``` -------------------------------- ### Create credentials from external account sources Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.external_account.html Factory methods to instantiate credentials from either a JSON file or a configuration mapping. These methods are used for external account authentication and require careful validation of the configuration to prevent security risks. ```python # Create from file creds = Credentials.from_file("path/to/credentials.json") # Create from mapping info creds = Credentials.from_info({"type": "external_account", ...}) ``` -------------------------------- ### Login to Google Cloud SDK for Application Default Credentials Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.html Command to log in to the Google Cloud SDK and set up application default credentials. This is a prerequisite for the `google.auth.default()` function to use SDK credentials. ```bash gcloud auth application-default login ``` -------------------------------- ### Get Quota Project ID Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.aws.html This property returns the project to be used for quota and billing purposes. ```python @property def _quota_project_id(self) -> Optional[str]: """ Project to use for quota and billing purposes. """ pass ``` -------------------------------- ### Create Credentials with Quota Project in Python Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/downscoped.html Returns a new instance of credentials with an updated quota project ID. This is useful for specifying a different project for billing or quota purposes. It takes the quota_project_id as an argument and returns a new Credentials object. ```python @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) def with_quota_project(self, quota_project_id): return self.__class__( self._source_credentials, self._credential_access_boundary, quota_project_id=quota_project_id, ) ``` -------------------------------- ### Get Credentials' Current Set of Scopes Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.aws.html This property returns the current set of scopes associated with the credentials as a sequence of strings. ```python @property def _scopes(self) -> Sequence[str]: """ the credentials’ current set of scopes. """ pass ``` -------------------------------- ### Initialize Application Default SSL Credentials Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/transport/grpc.html Shows how to use application default SSL credentials for context-aware metadata, typically used in environments with endpoint verification support. ```python try: default_ssl_credentials = SslCredentials() except: # Exception can be raised if the context aware metadata is malformed. pass if default_ssl_credentials.is_mtls: endpoint_to_use = mtls_endpoint else: endpoint_to_use = regular_endpoint channel = google.auth.transport.grpc.secure_authorized_channel( credentials, request, endpoint_to_use, ssl_credentials=default_ssl_credentials) ``` -------------------------------- ### Get Project Number for Workload Identity Pool Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.aws.html This property returns the project number corresponding to the workload identity pool as an optional string. ```python @property def _project_number(self) -> Optional[str]: """ The project number corresponding to the workload identity pool. """ pass ``` -------------------------------- ### Get STS Token Introspection Endpoint Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.aws.html This property returns the Security Token Service (STS) token introspection endpoint URL as an optional string. ```python @property def _token_info_url(self) -> Optional[str]: """ The STS token introspection endpoint. """ pass ``` -------------------------------- ### Get Service Account Email for Impersonation Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.aws.html This property returns the service account email if service account impersonation is being used. Otherwise, it returns None. ```python @property def _service_account_email(self) -> Optional[str]: """ Returns the service account email if service account impersonation is used. """ pass ``` -------------------------------- ### POST /credentials/with_quota_project Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth._credentials_async.html Creates a copy of the current credentials instance with a modified quota project ID for billing and usage tracking. ```APIDOC ## POST /credentials/with_quota_project ### Description Returns a new instance of the credentials object configured with a specific project ID for quota and billing purposes. ### Method POST ### Endpoint /credentials/with_quota_project ### Parameters #### Request Body - **quota_project_id** (string) - Required - The project ID to use for quota and billing. ### Request Example { "quota_project_id": "my-billing-project-123" } ### Response #### Success Response (200) - **credentials** (object) - A new credentials instance with the updated project ID. #### Response Example { "status": "success", "message": "Credentials updated with new quota project." } ``` -------------------------------- ### Initialize OnDemandCredentials from Signing Credentials Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth._jwt_async.html Demonstrates how to create an OnDemandCredentials instance using an existing service account credentials object. This is useful for migrating from standard service account authentication to on-demand JWT authentication. ```python from google.auth import service_account from google.auth.jwt import OnDemandCredentials # Load existing service account credentials svc_creds = service_account.Credentials.from_service_account_file('service_account.json') # Create OnDemandCredentials from the existing signer jwt_creds = OnDemandCredentials.from_signing_credentials(svc_creds) ``` -------------------------------- ### Verify ID Tokens Source: https://googleapis.dev/python/google-auth/latest/user-guide.html Shows how to verify ID tokens using the google.oauth2.id_token module, which supports RS256 and ES256 algorithms. ```python from google.oauth2 import id_token import google.auth.transport.requests request = google.auth.transport.requests.Request() try: decoded_token = id_token.verify_token(token_to_verify, request) except ValueError: # Verification failed. ``` -------------------------------- ### Get Cached or New JWT Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/jwt.html Retrieves a JWT for a given audience from the cache if it's valid and not expired. Otherwise, it generates a new JWT and caches it. ```python token, expiry = self._cache.get(audience, (None, None)) if token is None or expiry < _helpers.utcnow(): token, expiry = self._make_jwt_for_audience(audience) self._cache[audience] = token, expiry return token ``` -------------------------------- ### Get the Signer Email from JWT Credentials (Python) Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/jwt.html Returns the email address of the signer used for the JWT. This property is derived from the issuer claim of the JWT. ```python return self._issuer ``` -------------------------------- ### Initialize Service Account Credentials Source: https://googleapis.dev/python/google-auth/latest/_modules/google/oauth2/_service_account_async.html Demonstrates how to instantiate service account credentials using a JSON key file or a loaded dictionary. These credentials support optional scopes and subject delegation. ```python import json # From file credentials = Credentials.from_service_account_file('service-account.json') # From dictionary service_account_info = json.load(open('service-account.json')) credentials = Credentials.from_service_account_info(service_account_info) # With scopes and subject credentials = Credentials.from_service_account_file( 'service-account.json', scopes=['email'], subject='user@example.com' ) ``` -------------------------------- ### Initialize and Use AuthorizedHttp for API Requests Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/transport/urllib3.html Shows how to instantiate the AuthorizedHttp class with credentials and perform authenticated HTTP requests to Google Cloud APIs. ```python from google.auth.transport.urllib3 import AuthorizedHttp authed_http = AuthorizedHttp(credentials) response = authed_http.request('GET', 'https://www.googleapis.com/storage/v1/b') ``` -------------------------------- ### Get Google Cloud Project ID Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/compute_engine/_metadata.html Retrieves the project ID associated with the current GCE instance from the metadata server. ```python def get_project_id(request): """Get the Google Cloud Project ID from the metadata server.""" # Implementation would call get_metadata with the appropriate path pass ``` -------------------------------- ### GET /v1/projects/-/serviceAccounts/{serviceAccount}/allowedLocations Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/compute_engine/credentials.html Retrieves the allowed locations for a specific service account within the IAM credentials service. ```APIDOC ## GET /v1/projects/-/serviceAccounts/{serviceAccount}/allowedLocations ### Description Retrieves the allowed locations for a given service account to enforce trust boundary constraints. ### Method GET ### Endpoint https://iamcredentials.{universe_domain}/v1/projects/-/serviceAccounts/{serviceAccount}/allowedLocations ### Parameters #### Path Parameters - **serviceAccount** (string) - Required - The email address or unique ID of the service account. ### Request Example GET https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/my-sa@project.iam.gserviceaccount.com/allowedLocations ### Response #### Success Response (200) - **allowedLocations** (list) - A list of regions or locations where the service account is permitted to operate. #### Response Example { "allowedLocations": ["us-central1", "europe-west1"] } ``` -------------------------------- ### Create IDTokenCredentials from Service Account Info (Python) Source: https://googleapis.dev/python/google-auth/latest/reference/google.oauth2.service_account.html Illustrates creating IDTokenCredentials from already loaded service account information. This is useful when the service account details are available in memory, such as after parsing a JSON file. Additional constructor arguments can be passed through. ```python import json from google.auth import service_account service_account_info = json.load(open('service_account.json')) credentials = ( service_account.IDTokenCredentials.from_service_account_info( service_account_info)) ``` -------------------------------- ### Encode URL Request Parameters Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.transport.urllib3.html Describes the request_encode_url function used to perform HTTP requests like GET, HEAD, or DELETE by encoding fields directly into the request URL. ```python def request_encode_url(method: str, url: str, fields: Sequence[tuple[str, str | bytes]] | Mapping[str, str | bytes] | None = None, headers: Mapping[str, str] | None = None, **urlopen_kw: str) -> BaseHTTPResponse: ``` -------------------------------- ### External Account Credentials Constructor Source: https://googleapis.dev/python/google-auth/latest/_modules/google/auth/identity_pool.html This section details the constructor for the `Credentials` class, outlining its parameters, potential exceptions, and usage notes. It explains how to provide credential sources or subject token suppliers for token retrieval. ```APIDOC ## Credentials Constructor ### Description Initializes an instance of the `Credentials` class for retrieving Google access tokens using external credential sources. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **audience** (Optional [str]) - The audience for the token. * **subject_token_type** (Optional [str]) - The type of the subject token. * **token_url** (Optional [str]) - The STS endpoint URL. Defaults to "https://sts.googleapis.com/v1/token". * **credential_source** (Optional [Mapping]) - A dictionary providing instructions on how to retrieve external credentials. Must be provided along with either a `subject_token_supplier` or be sufficient on its own. * Example for URL-sourced credential: ```json { "url": "http://www.example.com", "format": { "type": "json", "subject_token_field_name": "access_token" }, "headers": {"foo": "bar"} } ``` * Example for file-sourced credential: ```json { "file": "/path/to/token/file.txt" } ``` * **subject_token_supplier** (Optional [SubjectTokenSupplier]) - An optional supplier for the subject token. Must be provided along with either a `credential_source` or be sufficient on its own. * **args** (List) - Optional positional arguments passed to the underlying `external_account.Credentials.__init__` method. * **kwargs** (Mapping) - Optional keyword arguments passed to the underlying `external_account.Credentials.__init__` method. ### Request Example ```python from google.auth.external_account import Credentials # Example using a credential source (URL) creds_url = Credentials( audience="my-audience", subject_token_type="urn:ietf:params:oauth:token-type:jwt", credential_source={ "url": "http://example.com/token", "format": {"type": "json", "subject_token_field_name": "access_token"}, "headers": {"X-Custom-Header": "value"} } ) # Example using a credential source (file) creds_file = Credentials( audience="my-audience", subject_token_type="urn:ietf:params:oauth:token-type:jwt", credential_source={ "file": "/path/to/credential.json" } ) # Example using a subject token supplier (requires separate implementation of SubjectTokenSupplier) # class MyTokenSupplier(SubjectTokenSupplier): # def get_subject_token(self): # return "my-subject-token" # # creds_supplier = Credentials( # audience="my-audience", # subject_token_type="urn:ietf:params:oauth:token-type:jwt", # subject_token_supplier=MyTokenSupplier() # ) ``` ### Response #### Success Response (200) N/A (This is a constructor, it does not return a response in the typical API sense. It initializes an object.) #### Response Example N/A ### Raises * **google.auth.exceptions.RefreshError**: If an error is encountered during access token retrieval logic. * **ValueError**: For invalid parameters. * **google.auth.exceptions.InvalidValue**: If neither a credential source nor a subject token supplier is provided, or if both are provided. * **google.auth.exceptions.MalformedError**: If the `credential_source` is malformed (e.g., not a dictionary, or contains unsupported fields like `environment_id`). ``` -------------------------------- ### Get Credential Information Source: https://googleapis.dev/python/google-auth/latest/reference/google.auth.compute_engine.html Retrieves credential information as a JSON mapping. This information is useful for inclusion in authentication-related error messages generated by client libraries. ```python cred_info = credentials.get_cred_info() print(cred_info) ``` -------------------------------- ### Get Credential Information in Python Source: https://googleapis.dev/python/google-auth/latest/_modules/google/oauth2/credentials.html Retrieves information about the credential, including its source and type. If the credential is file-based and an account is associated, it returns a dictionary with 'credential_source', 'credential_type', and 'principal'. Otherwise, it returns None. ```python if self._cred_file_path: cred_info = { "credential_source": self._cred_file_path, "credential_type": "user credentials", } if self.account: cred_info["principal"] = self.account return cred_info return None ``` -------------------------------- ### Initialize Storage Client with OAuth2 Credentials Source: https://googleapis.dev/python/google-auth/latest/_sources/user-guide.rst.txt Initializes a Google Cloud Storage client using OAuth2 credentials. This example demonstrates how to create credentials with optional downscoped tokens and expiry, and then use them to instantiate the storage client. It assumes the existence of a refresh handler function. ```python import google.oauth2.credentials from google.cloud import storage # Assume downscoped_token, expiry, and get_token_from_broker are defined elsewhere credentials = google.oauth2.credentials.Credentials( downscoped_token, expiry=expiry, scopes=['https://www.googleapis.com/auth/cloud-platform'], refresh_handler=get_token_from_broker) # Initialize a storage client with the oauth2 credentials. storage_client = storage.Client( project='my_project_id', credentials=credentials) # Call GCS APIs. # The token broker has readonly access to objects starting with "customer-a" # in bucket "bucket-123". bucket = storage_client.bucket('bucket-123') blob = bucket.blob('customer-a-data.txt') print(blob.download_as_bytes().decode("utf-8")) ```