### Mutual TLS Configuration Example Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.transport.requests.md Example of how to configure mutual TLS using a callback for certificate and key. ```APIDOC ## Configure Mutual TLS ### Description This example demonstrates how to configure mutual TLS (mTLS) for an authenticated session. It shows the use of a callback function to provide client certificates and keys, and includes error handling. ### Method `configure_mtls_channel` ### Endpoint N/A (This is a method call, not a direct endpoint) ### Request Example ```python try: authed_session.configure_mtls_channel(my_cert_callback) except Exception as e: # Handle exceptions, e.g., MutualTLSChannelError print(f"Error configuring mTLS: {e}") ``` ### Response This method does not return a value directly but configures the session for mTLS. Success is indicated by the absence of exceptions. The `is_mtls` property can be checked after configuration. ### Error Handling * `google.auth.exceptions.MutualTLSChannelError`: Raised if mutual TLS channel creation fails. * General exceptions during callback execution or credential retrieval. ``` -------------------------------- ### Manage Scoped Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.credentials.md Examples for checking scope requirements and applying scopes to credentials. ```default if credentials.requires_scopes: # Scoping is required. credentials = credentials.with_scopes(scopes=['one', 'two']) ``` ```default credentials = SomeScopedCredentials(scopes=['one', 'two']) ``` ```default scoped_credentials = credentials.with_scopes(scopes=['one', 'two']) ``` -------------------------------- ### AWS Credential Source Example Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.aws.md Example of a credential source dictionary for AWS credentials. This dictionary provides instructions for retrieving external credentials to be exchanged for Google access tokens. ```python { "environment_id": "aws1", "regional_cred_verification_url": "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15", "region_url": "http://169.254.169.254/latest/meta-data/placement/availability-zone", "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials", "imdsv2_session_token_url": "http://169.254.169.254/latest/api/token" } ``` -------------------------------- ### Create IDTokenCredentials from Service Account Info Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2._service_account_async.md Use this constructor when you already have the service account information loaded, for example, from a JSON file parsed into a dictionary. Additional arguments like scopes and subject can be provided. ```python service_account_info = json.load(open('service_account.json')) credentials = ( _service_account_async.IDTokenCredentials.from_service_account_info( service_account_info)) ``` -------------------------------- ### Using Application Default SSL Credentials for mTLS Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.transport.requests.md Example of configuring mutual TLS using application default SSL credentials. ```APIDOC ## Configure Mutual TLS with Application Defaults ### Description This example shows how to configure mutual TLS (mTLS) for an authenticated session using application default SSL credentials. This is a simpler approach when credentials can be automatically discovered. ### Method `configure_mtls_channel()` ### Endpoint N/A (This is a method call, not a direct endpoint) ### Request Example ```python try: authed_session.configure_mtls_channel() except Exception as e: # Handle exceptions, e.g., MutualTLSChannelError print(f"Error configuring mTLS with application defaults: {e}") ``` ### Response Similar to the callback method, this configures the session for mTLS without returning a direct value. Check the `is_mtls` property for confirmation. ### Error Handling * `google.auth.exceptions.MutualTLSChannelError`: Raised if mutual TLS channel creation fails using application defaults. ``` -------------------------------- ### Create Service Account Credentials from Info (Async) Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2._service_account_async.md Use this helper constructor to create asynchronous service account credentials when the service account information is already loaded. The info should be a dictionary. ```python service_account_info = json.load(open('service-account.json')) credentials = _service_account_async.Credentials.from_service_account_info( service_account_info) ``` -------------------------------- ### Initialize source credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.impersonated_credentials.md Load service account credentials from a JSON file to serve as the base for impersonation. ```python from google.oauth2 import service_account target_scopes = [ 'https://www.googleapis.com/auth/devstorage.read_only'] source_credentials = ( service_account.Credentials.from_service_account_file( '/path/to/svc_account.json', scopes=target_scopes)) ``` -------------------------------- ### Subject Token Type Example Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.aws.md An example of a subject token type based on the OAuth2.0 token exchange specification. This is expected when exchanging AWS credentials for Google access tokens. ```default “urn:ietf:params:aws:token-type:aws4_request” ``` -------------------------------- ### Create Service Account Credentials from File (Async) Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2._service_account_async.md Use this helper constructor to create asynchronous service account credentials from a JSON private key file. Ensure the file path is correct. ```python credentials = _service_account_async.Credentials.from_service_account_file( 'service-account.json') ``` -------------------------------- ### Credentials - token_state Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.impersonated_credentials.md Gets the token state. ```APIDOC ## token_state ### Description See :obj:`TokenState` ``` -------------------------------- ### Create User Credentials Instance Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Instantiate credentials using an access token, with optional support for automatic refreshing via refresh tokens. ```python import google.oauth2.credentials credentials = google.oauth2.credentials.Credentials( 'access_token') ``` ```python credentials = google.oauth2.credentials.Credentials( 'access_token', refresh_token='refresh_token', token_uri='token_uri', client_id='client_id', client_secret='client_secret') ``` -------------------------------- ### Credentials - universe_domain Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.impersonated_credentials.md Gets the universe domain value. ```APIDOC ## universe_domain ### Description The universe domain value. ### Type `str` ``` -------------------------------- ### Credentials - scopes Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.impersonated_credentials.md Gets the credentials' current set of scopes. ```APIDOC ## scopes ### Description The credentials’ current set of scopes. ### Type `Sequence` `str` ``` -------------------------------- ### Initialize default credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Automatically choose the client type and initialize credentials from the configured environment. ```default import google.auth credentials, project = google.auth.default() ``` -------------------------------- ### Credentials - quota_project_id Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.impersonated_credentials.md Gets the project to use for quota and billing purposes. ```APIDOC ## quota_project_id ### Description Project to use for quota and billing purposes. ### Type `str` ``` -------------------------------- ### Configure AuthorizedHttp for mTLS Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.transport.urllib3.md Setup AuthorizedHttp instance for mutual TLS communication. ```python regular_endpoint = 'https://pubsub.googleapis.com/v1/projects/{my_project_id}/topics' mtls_endpoint = 'https://pubsub.mtls.googleapis.com/v1/projects/{my_project_id}/topics' authed_http = AuthorizedHttp(credentials) ``` -------------------------------- ### Create Service Account Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2.service_account.md Helper methods to initialize credentials from a JSON file or a loaded dictionary. ```python credentials = service_account.Credentials.from_service_account_file( 'service-account.json') ``` ```python service_account_info = json.load(open('service_account.json')) credentials = service_account.Credentials.from_service_account_info( service_account_info) ``` -------------------------------- ### Configure Credentials with Scopes and Subject Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2.service_account.md Pass additional arguments like scopes and subject during credential initialization. ```python credentials = service_account.Credentials.from_service_account_file( 'service-account.json', scopes=['email'], subject='user@example.com') ``` -------------------------------- ### Configure Cloud SDK for Application Default Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.md Commands to authenticate and set the active project for the Google Cloud SDK. ```default gcloud auth application-default login ``` ```default gcloud config set project ``` -------------------------------- ### request_encode_url Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.transport.urllib3.md Encodes fields directly into the request URL, typically used for GET, HEAD, or DELETE requests. ```APIDOC ## request_encode_url ### Description Make a request using urlopen() with the fields encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. ### Parameters #### Query Parameters - **method** (str) - Required - HTTP request method (such as GET, POST, PUT, etc.) - **url** (str) - Required - The URL to perform the request on. - **fields** (Sequence/Mapping) - Optional - Data to encode and send in the URL. - **headers** (Mapping) - Optional - Dictionary of custom headers to send. ``` -------------------------------- ### Making Authenticated Requests Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.transport.requests.md Demonstrates how to make authenticated GET requests, conditionally using mTLS or regular endpoints. ```APIDOC ## Making Authenticated Requests ### Description This example illustrates how to make authenticated HTTP requests using an `AuthedSession`. It shows conditional logic to use a mutual TLS (mTLS) endpoint if mTLS is enabled, otherwise falling back to a regular endpoint. ### Method `request` (and its convenience methods like `get`) ### Endpoint `mtls_endpoint` or `regular_endpoint` (These are placeholders for actual URLs) ### Request Example ```python # Assuming authed_session is an initialized AuthedSession object if authed_session.is_mtls: response = authed_session.request('GET', mtls_endpoint) else: response = authed_session.request('GET', regular_endpoint) # Process the response print(response.status_code) print(response.text) ``` ### Response * **Success Response (200 OK)**: Typically a `requests.Response` object containing the server's response. * `status_code` (int) - The HTTP status code of the response. * `text` (str) - The response body as a string. ### Error Handling * `google.auth.exceptions.MutualTLSChannelError`: If mTLS channel creation fails during the request. * `requests.exceptions.RequestException`: For general network or HTTP errors during the request. ``` -------------------------------- ### Create IDTokenCredentials from a service account file Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2.service_account.md Initializes credentials using a path to a service account JSON file. ```python credentials = ( service_account.IDTokenCredentials.from_service_account_file( 'service-account.json')) ``` -------------------------------- ### Initialize External Account Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.identity_pool.md Instantiates an external account credentials object from a file/URL. Typically, helper constructors like from_file() or from_info() are used instead of calling the constructor directly. ```python Credentials( audience='my-audience', subject_token_type='urn:ietf:params:oauth:token-type:jwt', token_url='https://sts.googleapis.com/v1/token', credential_source={ "url": "http://www.example.com", "format": { "type": "json", "subject_token_field_name": "access_token", }, "headers": {"foo": "bar"}, }, ) ``` ```python Credentials( audience='my-audience', subject_token_type='urn:ietf:params:oauth:token-type:jwt', credential_source={ "file": "/path/to/token/file.txt" }, ) ``` -------------------------------- ### Get Credential Information Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.identity_pool.md Retrieves the credential information JSON, which is added to auth-related error messages by the client library. ```python cred_info = credentials.get_cred_info() ``` -------------------------------- ### Create JWT Credentials from Service Account File Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth._jwt_async.md Initializes credentials using a service account JSON file path. ```python audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher' credentials = jwt_async.Credentials.from_service_account_file( 'service-account.json', audience=audience) ``` -------------------------------- ### Define fields for multipart request Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.transport.urllib3.md Example structure for the fields parameter, supporting simple key-value pairs and file uploads with optional MIME types. ```python fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } ``` -------------------------------- ### Load Credentials from Service Account File Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Obtain credentials from a service account private key file using `service_account.Credentials.from_service_account_file`. You can then specify the desired scopes. ```python from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file( '/path/to/key.json') scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/cloud-platform']) ``` -------------------------------- ### Get Default Encrypted Client Certificate Source Callback Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.transport.mtls.md Retrieves a callback function for default encrypted client SSL credentials, writing to specified file paths. ```APIDOC ## default_client_encrypted_cert_source(cert_path, key_path) ### Description Get a callback which returns the default encrypted client SSL credentials. The certificate and private key will be written to the provided file paths. ### Method GET ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **cert_path** (str) - Required - The file path where the default client certificate will be written. - **key_path** (str) - Required - The file path where the default encrypted client key will be written. ### Response #### Success Response (200) - **callback** (Callable, str, str, bytes) - A callback which generates the default client certificate, encrypted 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. ### Response Example ```json { "callback": "" } ``` ### Raises - **google.auth.exceptions.DefaultClientCertSourceError** – If any problem occurs when loading or saving the client certificate and key. ``` -------------------------------- ### Create IDTokenCredentials with additional parameters Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2.service_account.md Initializes credentials from a file while specifying additional scopes and a subject for delegation. ```python credentials = ( service_account.IDTokenCredentials.from_service_account_file( 'service-account.json', scopes=['email'], subject='user@example.com')) ``` -------------------------------- ### Initialize App Engine Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Use the app_engine module to create a credentials instance specifically for the App Engine standard environment. ```python from google.auth import app_engine credentials = app_engine.Credentials() ``` -------------------------------- ### Get Default Client Certificate Source Callback Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.transport.mtls.md Retrieves a callback function that returns the default client SSL credentials (certificate and private key in PEM format). ```APIDOC ## default_client_cert_source() ### Description Get a callback which returns the default client SSL credentials. ### Method GET ### Endpoint N/A (Function Call) ### Parameters None ### Response #### Success Response (200) - **callback** (Callable, bytes, bytes) - A callback which returns the default client certificate bytes and private key bytes, both in PEM format. ### Response Example ```json { "callback": "" } ``` ### Raises - **google.auth.exceptions.DefaultClientCertSourceError** – If the default client SSL credentials don’t exist or are malformed. ``` -------------------------------- ### Verify ID Token Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Use `id_token.verify_token` to verify an ID token. This method supports RS256 and ES256 algorithms. Ensure the `cryptography` dependency is installed for ES256 support. ```python from google.auth2 import id_token request = google.auth.transport.requests.Request() try: decoded_token = id_token.verify_token(token_to_verify,request) except ValueError: # Verification failed. ``` -------------------------------- ### Apply Principle of Least Privilege with Downscoped Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Initializes a storage client directly with downscoped credentials to limit access. ```python # Create the downscoped credentials. downscoped_credentials = downscoped.Credentials( # source_credentials have elevated access but only a subset of # these permissions are needed here. source_credentials=source_credentials, credential_access_boundary=credential_access_boundary) # Pass the token directly. storage_client = storage.Client( project='my_project_id', credentials=downscoped_credentials) # If the source credentials have elevated levels of access, the # token in flight here will have limited 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_string()) ``` -------------------------------- ### Create JWT Credentials with Additional Claims Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth._jwt_async.md Initializes credentials from a file while specifying custom JWT claims. ```python credentials = jwt_async.Credentials.from_service_account_file( 'service-account.json', audience=audience, additional_claims={'meta': 'data'}) ``` -------------------------------- ### Generate URL-Sourced OIDC Config Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md This command generates an OIDC configuration for URL-sourced credentials. A local server must host a GET endpoint that returns the OIDC token, potentially with specified headers. ```bash # Generate an OIDC configuration file for URL-sourced credentials. gcloud iam workforce-pools create-cred-config \ locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ --credential-source-url=$URL_TO_RETURN_OIDC_ID_TOKEN \ --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ --output-file=/path/to/generated/config.json ``` -------------------------------- ### Creating Credentials from Service Account File Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2.service_account.md Instantiates `Credentials` using a service account JSON file. ```APIDOC ## POST /api/users ### Description Creates a Credentials instance from a service account json file. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters - **filename** (str) - Required - The path to the service account json file. #### Query Parameters - **scopes** (Sequence[str]) - Optional - User-defined scopes to request during the authorization grant. - **subject** (str) - Optional - For domain-wide delegation, the email address of the user to for which to request delegated access. ### Request Example ```json { "filename": "service-account.json", "scopes": ["email", "profile"], "subject": "user@example.com" } ``` ### Response #### Success Response (200) - **credentials** (google.auth.service_account.Credentials) - The constructed credentials. #### Response Example ```json { "credentials": "" } ``` ``` -------------------------------- ### Generate X.509 Credential Configuration Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Commands to create credential configuration files for X.509 workload identity federation using default or custom paths. ```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 ``` -------------------------------- ### Fetch ID Token from Environment Source: https://context7.com/googleapis/google-auth-library-python/llms.txt Automatically fetch ID tokens from the environment using Application Default Credentials. This method is the simplest for obtaining tokens for services like Cloud Run. You can fetch the token directly or get a credentials object for more control. ```python import google.oauth2.id_token import google.auth.transport.requests request = google.auth.transport.requests.Request() target_audience = 'https://my-cloud-run-service.run.app' # Fetch ID token directly (simplest method) token = google.oauth2.id_token.fetch_id_token(request, target_audience) print(f"ID Token: {token}") # Or get credentials object for more control credentials = google.oauth2.id_token.fetch_id_token_credentials( target_audience, request=request ) credentials.refresh(request) print(f"Token: {credentials.token}") print(f"Expiry: {credentials.expiry}") ``` -------------------------------- ### Initialize AWS credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Explicitly initialize credentials using AWS configuration info. ```default import json from google.auth import aws json_config_info = json.loads(function_to_get_json_config()) credentials = aws.Credentials.from_info(json_config_info) scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/cloud-platform']) ``` -------------------------------- ### Create JWT Credentials from Service Account Info Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth._jwt_async.md Initializes credentials using a pre-loaded dictionary of service account information. ```python service_account_info = json.load(open('service-account.json')) credentials = jwt_async.Credentials.from_service_account_info( service_account_info, audience=audience) ``` -------------------------------- ### Configure gRPC with AuthMetadataPlugin Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Manually create a gRPC channel using AuthMetadataPlugin and composite channel credentials. ```python import grpc metadata_plugin = AuthMetadataPlugin(credentials, http_request) # Create a set of grpc.CallCredentials using the metadata plugin. google_auth_credentials = grpc.metadata_call_credentials( metadata_plugin) # Create SSL channel credentials. ssl_credentials = grpc.ssl_channel_credentials() # Combine the ssl credentials and the authorization credentials. composite_credentials = grpc.composite_channel_credentials( ssl_credentials, google_auth_credentials) channel = grpc.secure_channel( 'pubsub.googleapis.com:443', composite_credentials) ``` -------------------------------- ### Method: from_service_account_file Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth._jwt_async.md Creates a Credentials instance from a service account JSON file. ```APIDOC ## Method: from_service_account_file ### Description Creates a Credentials instance from a service account .json file in Google format. ### Parameters - **filename** (str) - Required - The path to the service account .json file. - **kwargs** (dict) - Optional - Additional arguments to pass to the constructor. ### Response - **credentials** (google.auth.jwt.Credentials) - The constructed credentials instance. ``` -------------------------------- ### Create Service Account Credentials with Scopes and Subject (Async) Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2._service_account_async.md When creating asynchronous service account credentials, you can specify additional scopes and a subject for delegation. This is useful for domain-wide delegation. ```python credentials = _service_account_async.Credentials.from_service_account_file( 'service-account.json', scopes=['email'], subject='user@example.com') ``` -------------------------------- ### Constructor: jwt_async.Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth._jwt_async.md Initializes a new instance of JWT credentials for asynchronous authentication. ```APIDOC ## Constructor: jwt_async.Credentials ### Description Creates credentials that use a JWT as the bearer token for asynchronous requests. ### Parameters - **signer** (google.auth.crypt.Signer) - Required - The signer used to sign JWTs. - **issuer** (str) - Required - The iss claim. - **subject** (str) - Required - The sub claim. - **audience** (str) - Required - The aud claim (intended recipient). - **additional_claims** (Mapping) - Optional - Additional claims for the JWT payload. - **token_lifetime** (int) - Optional - Token validity in seconds (default 3600). - **quota_project_id** (str) - Optional - Project ID for quota and billing. ``` -------------------------------- ### Service Account Credentials Constructor Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2.service_account.md The `Credentials` class is the base for service account credentials. It is typically instantiated using helper methods like `from_service_account_file` or `from_service_account_info`. ```APIDOC ## Credentials Constructor ### Description Represents service account credentials. Typically, you will use helper constructors like `from_service_account_file` or `from_service_account_info`. ### Parameters - **signer** (google.auth.crypt.Signer) - The signer used to sign JWTs. - **service_account_email** (str) - The service account’s email. - **token_uri** (str) - The OAuth 2.0 Token URI. - **scopes** (Sequence[str]) - User-defined scopes to request during the authorization grant. - **default_scopes** (Sequence[str]) - Default scopes passed by a Google client library. Use ‘scopes’ for user-defined scopes. - **subject** (str) - For domain-wide delegation, the email address of the user to for which to request delegated access. - **project_id** (str) - Project ID associated with the service account credential. - **quota_project_id** (Optional[str]) - The project ID used for quota and billing. - **additional_claims** (Mapping[str, str]) - Any additional claims for the JWT assertion used in the authorization grant. - **always_use_jwt_access** (Optional[bool]) - Whether self signed JWT should be always used. - **universe_domain** (str) - The universe domain. The default universe domain is googleapis.com. - **trust_boundary** (Mapping[str, str]) - A credential trust boundary. ### NOTE Typically one of the helper constructors `from_service_account_file()` or `from_service_account_info()` are used instead of calling the constructor directly. ``` -------------------------------- ### Retrieve Default Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.md Basic usage to obtain credentials and the associated project ID from the environment. ```default import google.auth credentials, project_id = google.auth.default() ``` -------------------------------- ### Initialize Azure and OIDC credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Explicitly initialize credentials using identity pool configuration info. ```default import json from google.auth import identity_pool json_config_info = json.loads(function_to_get_json_config()) credentials = identity_pool.Credentials.from_info(json_config_info) scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/cloud-platform']) ``` -------------------------------- ### classmethod from_file Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.external_account.md Creates a Credentials instance from an external account JSON file. ```APIDOC ## from_file(filename, **kwargs) ### Description Creates a Credentials instance from an external account JSON file. Note: This method does not validate the credential configuration; ensure the source is trusted before use. ### Parameters - **filename** (str) - Required - The path to the external account json file. - **kwargs** (dict) - Optional - Additional arguments to pass to the constructor. ### Returns - **Credentials** (google.auth.identity_pool.Credentials) - The constructed credentials instance. ``` -------------------------------- ### Create Credentials from Service Account Info Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.jwt.md Instantiate JWT credentials from a pre-loaded service account dictionary. ```APIDOC ## Create Credentials from Service Account Info ### Description Creates a `jwt.Credentials` instance from a dictionary containing service account information. This is useful if you have already parsed the service account file. ### Method `jwt.Credentials.from_service_account_info(info, **kwargs)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import json import google.auth.jwt as jwt service_account_info = json.load(open('service_account.json')) audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher' credentials = jwt.Credentials.from_service_account_info( service_account_info, audience=audience) ``` ### Response #### Success Response (200) * **credentials** (jwt.Credentials) - The constructed JWT credentials object. #### Response Example N/A #### Error Response * **google.auth.exceptions.MalformedError** - If the info is not in the expected format. ``` -------------------------------- ### Credential Instantiation Methods Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.identity_pool.md Methods to create Identity Pool credentials from external sources. ```APIDOC ## from_info(info, **kwargs) ### Description Creates an Identity Pool Credentials instance from parsed external account info. ### Parameters - **info** (Mapping[str, str]) - Required - The Identity Pool external account info in Google format. - **kwargs** (dict) - Optional - Additional arguments to pass to the constructor. ### Response - **Returns** (google.auth.identity_pool.Credentials) - The constructed credentials. ## from_file(filename, **kwargs) ### Description Creates an IdentityPool Credentials instance from an external account json file. ### Parameters - **filename** (str) - Required - The path to the IdentityPool external account json file. - **kwargs** (dict) - Optional - Additional arguments to pass to the constructor. ### Response - **Returns** (google.auth.identity_pool.Credentials) - The constructed credentials. ``` -------------------------------- ### Create JWT Credentials from Parsed Service Account Info Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.jwt.md Instantiate JWT credentials using pre-loaded and parsed service account information. Pass any additional arguments to the constructor. ```python service_account_info = json.load(open('service_account.json')) credentials = jwt.Credentials.from_service_account_info( service_account_info, audience=audience) ``` -------------------------------- ### apply Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2._credentials_async.md Applies the token to the authentication header. ```APIDOC ## apply(headers, token=None) ### Description Apply the token to the authentication header. ### Parameters #### Request Body - **headers** (Mapping) - Required - The HTTP request headers. - **token** (str) - Optional - If specified, overrides the current access token. ``` -------------------------------- ### from_impersonated_service_account_info Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.impersonated_credentials.md Creates a Credentials instance from parsed impersonated service account credentials info. ```APIDOC ## from_impersonated_service_account_info(info, scopes=None) ### Description Creates a Credentials instance from parsed impersonated service account credentials info. Note: This method does not validate the credential configuration. ### Parameters - **info** (Mapping[str, str]) - Required - The impersonated service account credentials info in Google format. - **scopes** (Sequence[str]) - Optional - List of scopes to include in the credentials. ### Errors - **InvalidType** - If the info[“source_credentials”] are not a supported impersonation type. - **InvalidValue** - If the info[“service_account_impersonation_url”] is not in the expected format. - **ValueError** - If the info is not in the expected format. ``` -------------------------------- ### from_service_account_info Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2._service_account_async.md Creates a Credentials instance from parsed service account info. ```APIDOC ## from_service_account_info ### Description Creates a Credentials instance from parsed service account info. ### Parameters #### Request Body - **info** (Mapping[str, str]) - Required - The service account info in Google format. - **kwargs** (dict) - Optional - Additional arguments to pass to the constructor. ### Response - **Returns** (google.auth.service_account.Credentials) - The constructed credentials. - **Raises** (ValueError) - If the info is not in the expected format. ``` -------------------------------- ### Initialize Downscoped Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Defines access boundary rules and creates downscoped credentials using source credentials from ADC. ```python # Initialize the credential access boundary rules. 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]) # Retrieve the source credentials via ADC. source_credentials, _ = google.auth.default() # Create the downscoped credentials. downscoped_credentials = downscoped.Credentials( source_credentials=source_credentials, credential_access_boundary=credential_access_boundary) # Refresh the tokens. downscoped_credentials.refresh(requests.Request()) # These values will need to be passed to the Token Consumer. access_token = downscoped_credentials.token expiry = downscoped_credentials.expiry ``` -------------------------------- ### Signer Class Methods Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.crypt.md Methods for constructing Signer instances from different private key formats. ```APIDOC ## Signer Class Bases: `object` Abstract base class for cryptographic signers. ### Methods #### *classmethod* from_string(key, key_id=None) Construct a Signer instance from a private key in PEM format. ##### Parameters - **key** (str) - Private key in PEM format. - **key_id** (str) - An optional key id used to identify the private key. ##### Returns The constructed signer. ##### Return type [google.auth.crypt.Signer](#google.auth.crypt.Signer) ##### Raises **ValueError** - If the key cannot be parsed as PKCS#1 or PKCS#8 in PEM format. #### *classmethod* from_service_account_file(filename) Creates a Signer instance from a service account .json file in Google format. ##### Parameters - **filename** (str) - The path to the service account .json file. ##### Returns The constructed signer. ##### Return type [google.auth.crypt.Signer](#google.auth.crypt.Signer) #### *classmethod* from_service_account_info(info) Creates a Signer instance instance from a dictionary containing service account info in Google format. ##### Parameters - **info** (Mapping[str, str]) - The service account info in Google format. ##### Returns The constructed signer. ##### Return type [google.auth.crypt.Signer](#google.auth.crypt.Signer) ##### Raises **ValueError** - If the info is not in the expected format. #### *abstract property* key_id The key ID used to identify this private key. ##### Type Optional[str] #### *abstract* sign(message) Signs a message. ##### Parameters - **message** (Union[str, bytes]) - The message to be signed. ##### Returns The signature of the message. ##### Return type bytes ``` -------------------------------- ### End-to-End ID Token Flow with Cloud Run Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Demonstrates a complete flow for obtaining an ID token using service account credentials and making an authenticated request to a Cloud Run endpoint using `AuthorizedSession`. Also shows how to print the token and verify it. ```python from google.oauth2 import id_token from google.oauth2 import service_account import google.auth import google.auth.transport.requests from google.auth.transport.requests import AuthorizedSession target_audience = 'https://your-cloud-run-app.a.run.app' url = 'https://your-cloud-run-app.a.run.app' creds = service_account.IDTokenCredentials.from_service_account_file( '/path/to/svc.json', target_audience=target_audience) authed_session = AuthorizedSession(creds) # make authenticated request and print the response, status_code resp = authed_session.get(url) print(resp.status_code) print(resp.text) # to verify an ID Token request = google.auth.transport.requests.Request() token = creds.token print(token) print(id_token.verify_token(token,request)) ``` -------------------------------- ### Fetch ID Token Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2.id_token.md Use this to create ID token credentials from the current environment. It attempts to use service account credentials or the metadata server. Ensure you have the necessary imports. ```python import google.oauth2.id_token import google.auth.transport.requests request = google.auth.transport.requests.Request() target_audience = "https://pubsub.googleapis.com" # Create ID token credentials. credentials = google.oauth2.id_token.fetch_id_token_credentials(target_audience, request=request) # Refresh the credential to obtain an ID token. credentials.refresh(request) id_token = credentials.token id_token_expiry = credentials.expiry ``` -------------------------------- ### Create JWT Credentials from Service Account File Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.jwt.md Use this method to create JWT credentials when you have the path to a service account JSON file. Ensure the 'audience' claim is specified. ```python audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher' credentials = jwt.Credentials.from_service_account_file( 'service-account.json', audience=audience) ``` -------------------------------- ### Generate executable-sourced workforce configuration Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Use this command to generate a configuration file for executable-sourced credentials. Ensure the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable is set to 1. ```bash # Generate a configuration file for executable-sourced credentials. gcloud iam workforce-pools create-cred-config \ locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ --subject-token-type=$SUBJECT_TOKEN_TYPE \ # The absolute path for the program, including arguments. # e.g. --executable-command="/path/to/command --foo=bar" --executable-command=$EXECUTABLE_COMMAND \ # Optional argument for the executable timeout. Defaults to 30s. # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ # Optional argument for the absolute path to the executable output file. # See below on how this argument impacts the library behaviour. # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ --output-file /path/to/generated/config.json ``` -------------------------------- ### Generate Executable Credential Configuration Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Use the gcloud command to create a configuration file for executable-sourced credentials. Substitute the placeholder variables with your specific project and pool details. ```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 \ --subject-token-type=$SUBJECT_TOKEN_TYPE \ --executable-command=$EXECUTABLE_COMMAND \ --output-file /path/to/generated/config.json ``` -------------------------------- ### from_authorized_user_info(info, scopes=None) Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.oauth2.credentials.md Creates a Credentials instance from parsed authorized user info. ```APIDOC ## from_authorized_user_info(info, scopes=None) ### Description Creates a Credentials instance from parsed authorized user info. ### Parameters #### Request Body - **info** (Mapping[str, str]) - Required - The authorized user info in Google format. - **scopes** (Sequence[str]) - Optional - List of scopes to include in the credentials. ### Response #### Success Response (200) - **credentials** (google.oauth2.credentials.Credentials) - The constructed credentials instance. ``` -------------------------------- ### Create OnDemandCredentials from Signing Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth._jwt_async.md Initializes a new OnDemandCredentials instance using an existing Signing credentials object. ```python svc_creds = service_account.Credentials.from_service_account_file( 'service_account.json') jwt_creds = jwt.OnDemandCredentials.from_signing_credentials( svc_creds) ``` -------------------------------- ### Credentials Methods and Properties Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.app_engine.md This section outlines the key methods and properties available on the Credentials object for managing authentication tokens and their associated metadata. ```APIDOC ## Credentials Class Documentation ### Description Provides methods and properties for managing authentication credentials, including token refresh, scope checking, and validity assessment. ### Methods #### before_request(request, method, url, headers) Performs credential-specific before request logic. Refreshes the credentials if necessary, then calls [`apply()`](#google.auth.app_engine.Credentials.apply) to apply the token to the authentication header. * **Parameters:** * **request** (*google.auth.transport.Request*) – The object used to make HTTP requests. * **method** (*str*) – The request’s HTTP method or the RPC method being invoked. * **url** (*str*) – The request’s URI or the RPC service’s URI. * **headers** (*Mapping*) – The request’s headers. #### get_cred_info() Returns the credential information JSON, which is added to auth related error messages by client library. * **Returns:** The credential information JSON. * **Return type:** Mapping[str, str] #### has_scopes(scopes) Checks if the credentials have the given scopes. * **Parameters:** * **scopes** (Sequence[str]) – The list of scopes to check. * **Returns:** True if the credentials have the given scopes. * **Return type:** bool ### Properties #### default_scopes * **Type:** Sequence[str] * **Description:** The credentials’ current set of default scopes. #### expired * **Description:** Checks if the credentials are expired. Credentials with `expiry` set to None are considered to never expire. * **Deprecated:** Deprecated since version v2.24.0: Prefer checking [`token_state`](#google.auth.app_engine.Credentials.token_state) instead. #### expiry * **Type:** Optional[datetime] * **Description:** When the token expires and is no longer valid. If this is None, the token is assumed to never expire. #### quota_project_id * **Description:** Project to use for quota and billing purposes. #### scopes * **Type:** Sequence[str] * **Description:** The credentials’ current set of scopes. #### token_state * **Description:** See :obj:`TokenState #### universe_domain * **Description:** The universe domain value. #### valid * **Description:** Checks the validity of the credentials. This is True if the credentials have a `token` and the token is not [`expired`](#google.auth.app_engine.Credentials.expired). * **Deprecated:** Deprecated since version v2.24.0: Prefer checking [`token_state`](#google.auth.app_engine.Credentials.token_state) instead. ``` -------------------------------- ### Async CredentialsWithQuotaProject Methods Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.md Details the asynchronous methods for CredentialsWithQuotaProject. ```APIDOC ## Async CredentialsWithQuotaProject ### Description Represents asynchronous credentials that include a quota project. ### Methods - `apply()`: Asynchronously applies the credentials to a request. - `before_request()`: Asynchronously prepares the request before it is sent. ### Properties - `expired`: Indicates if the credentials have expired. - `get_cred_info()`: Asynchronously retrieves credential information. ``` -------------------------------- ### Obtain Compute Engine Credentials Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/user-guide.md Explicitly initialize credentials for applications running on Compute Engine, Container Engine, or App Engine flexible environment. ```python from google.auth import compute_engine credentials = compute_engine.Credentials() ``` -------------------------------- ### Create Credentials from Service Account File Source: https://github.com/googleapis/google-auth-library-python/blob/main/docs/reference/google.auth.jwt.md Conveniently create JWT credentials by providing the path to a service account JSON file. ```APIDOC ## Create Credentials from Service Account File ### Description Creates a `jwt.Credentials` instance by loading information from a service account JSON file. This is a common way to authenticate when running applications outside of Google Cloud. ### Method `jwt.Credentials.from_service_account_file(filename, **kwargs)` ### Parameters #### Path Parameters * **filename** (str) - Required - The path to the service account .json file. #### Query Parameters None #### Request Body None ### Request Example ```python import google.auth.jwt as jwt audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher' credentials = jwt.Credentials.from_service_account_file( 'service-account.json', audience=audience) # You can also pass additional claims: credentials_with_claims = jwt.Credentials.from_service_account_file( 'service-account.json', audience=audience, additional_claims={'meta': 'data'}) ``` ### Response #### Success Response (200) * **credentials** (jwt.Credentials) - The constructed JWT credentials object. #### Response Example N/A ```