google.auth.identity_pool module

Identity Pool Credentials.

This module provides credentials to access Google Cloud resources from on-prem or non-Google Cloud platforms which support external credentials (e.g. OIDC ID tokens) retrieved from local file locations or local servers. This includes Microsoft Azure and OIDC identity providers (e.g. K8s workloads registered with Hub with Hub workload identity enabled).

These credentials are recommended over the use of service account credentials in on-prem/non-Google Cloud platforms as they do not involve the management of long-live service account private keys.

Identity Pool Credentials are initialized using external_account arguments which are typically loaded from an external credentials file or an external credentials URL.

This module also provides a definition for an abstract subject token supplier. This supplier can be implemented to return a valid OIDC or SAML2.0 subject token and used to create Identity Pool credentials. The credentials will then call the supplier instead of using pre-defined methods such as reading a local file or calling a URL.

class SubjectTokenSupplier[source]

Bases: object

Base class for subject token suppliers. This can be implemented with custom logic to retrieve a subject token to exchange for a Google Cloud access token when using Workload or Workforce Identity Federation. The identity pool credential does not cache the subject token, so caching logic should be added in the implementation.

abstract get_subject_token(context, request)[source]

Returns the requested subject token. The subject token must be valid.

Parameters:
  • context (google.auth.externalaccount.SupplierContext) – The context object containing information about the requested audience and subject token type.

  • request (google.auth.transport.Request) – The object used to make HTTP requests.

Raises:

google.auth.exceptions.RefreshError – If an error is encountered during subject token retrieval logic.

Returns:

The requested subject token string.

Return type:

str

class Credentials(audience, subject_token_type, token_url='https://sts.googleapis.com/v1/token', credential_source=None, subject_token_supplier=None, *args, **kwargs)[source]

Bases: Credentials

External account credentials sourced from files and URLs.

Instantiates an external account credentials object from a file/URL.

Parameters:
  • audience (str) – The STS audience field.

  • subject_token_type (str) –

    The subject token type based on the Oauth2.0 token exchange spec. Expected values include:

    “urn:ietf:params:oauth:token-type:jwt”
    “urn:ietf:params:oauth:token-type:id-token”
    “urn:ietf:params:oauth:token-type:saml2”
    

  • token_url (Optional [str]) – The STS endpoint URL. If not provided, will default to “https://sts.googleapis.com/v1/token”.

  • credential_source (Optional [Mapping]) –

    The credential source dictionary used to provide instructions on how to retrieve external credential to be exchanged for Google access tokens. Either a credential source or a subject token supplier must be provided.

    Example credential_source for url-sourced credential:

    {
        "url": "http://www.example.com",
        "format": {
            "type": "json",
            "subject_token_field_name": "access_token",
        },
        "headers": {"foo": "bar"},
    }
    

    Example credential_source for file-sourced credential:

    {
        "file": "/path/to/token/file.txt"
    }
    

  • subject_token_supplier (Optional [SubjectTokenSupplier]) – Optional subject token supplier. This will be called to supply a valid subject token which will then be exchanged for Google access tokens. Either a subject token supplier or a credential source must be provided.

  • args (List) – Optional positional arguments passed into the underlying __init__() method.

  • kwargs (Mapping) – Optional keyword arguments passed into the underlying __init__() method.

Raises:

Note

Typically one of the helper constructors from_file() or from_info() are used instead of calling the constructor directly.

retrieve_subject_token(request)[source]

Retrieves the subject token using the credential_source object.

Parameters:

request (google.auth.transport.Request) – A callable used to make HTTP requests.

Returns:

The retrieved subject token.

Return type:

str

apply(headers, token=None)[source]

Apply the token to the authentication header.

Parameters:
  • headers (Mapping) – The HTTP request headers.

  • token (Optionalstr) – If specified, overrides the current access token.

before_request(request, method, url, headers)[source]

Performs credential-specific before request logic.

Refreshes the credentials if necessary, then calls 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.

property default_scopes

the credentials’ current set of default scopes.

Type:

Sequencestr

property expired

Checks if the credentials are expired.

Note that credentials can be invalid but not expired because Credentials with expiry set to None is considered to never expire.

Deprecated since version v2.24.0: Prefer checking token_state instead.

get_project_id(request)[source]

Retrieves the project ID corresponding to the workload identity or workforce pool. For workforce pool credentials, it returns the project ID corresponding to the workforce_pool_user_project.

When not determinable, None is returned.

This is introduced to support the current pattern of using the Auth library:

credentials, project_id = google.auth.default()

The resource may not have permission (resourcemanager.projects.get) to call this API or the required scopes may not be selected: https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes

Parameters:

request (google.auth.transport.Request) – A callable used to make HTTP requests.

Returns:

The project ID corresponding to the workload identity pool

or workforce pool if determinable.

Return type:

Optionalstr

has_scopes(scopes)

Checks if the credentials have the given scopes.

Parameters:

scopes (Sequencestr) – The list of scopes to check.

Returns:

True if the credentials have the given scopes.

Return type:

bool

property info

Generates the dictionary representation of the current credentials.

Returns:

The dictionary representation of the credentials. This is the

reverse of “from_info” defined on the subclasses of this class. It is useful for serializing the current credentials so it can deserialized later.

Return type:

Mapping

property is_user

Returns whether the credentials represent a user (True) or workload (False). Workloads behave similarly to service accounts. Currently workloads will use service account impersonation but will eventually not require impersonation. As a result, this property is more reliable than the service account email property in determining if the credentials represent a user or workload.

Returns:

True if the credentials represent a user. False if they represent a

workload.

Return type:

bool

property is_workforce_pool

Returns whether the credentials represent a workforce pool (True) or workload (False) based on the credentials’ audience.

This will also return True for impersonated workforce pool credentials.

Returns:

True if the credentials represent a workforce pool. False if they

represent a workload.

Return type:

bool

property project_number

The project number corresponding to the workload identity pool.

Type:

Optionalstr

property quota_project_id

Project to use for quota and billing purposes.

refresh(request)[source]

Refreshes the access token.

Parameters:

request (google.auth.transport.Request) – The object used to make HTTP requests.

Raises:

google.auth.exceptions.RefreshError – If the credentials could not be refreshed.

property requires_scopes

Checks if the credentials requires scopes.

Returns:

True if there are no scopes set otherwise False.

Return type:

bool

property scopes

the credentials’ current set of scopes.

Type:

Sequencestr

property service_account_email

Returns the service account email if service account impersonation is used.

Returns:

The service account email if impersonation is used. Otherwise

None is returned.

Return type:

Optionalstr

property token_info_url

The STS token introspection endpoint.

Type:

Optionalstr

property token_state

See :obj:`TokenState

property universe_domain

The universe domain value.

property valid

Checks the validity of the credentials.

This is True if the credentials have a token and the token is not expired.

Deprecated since version v2.24.0: Prefer checking token_state instead.

with_quota_project(quota_project_id)[source]

Returns a copy of these credentials with a modified quota project.

Parameters:

quota_project_id (str) – The project to use for quota and billing purposes

Returns:

A new credentials instance.

Return type:

google.auth.credentials.Credentials

with_scopes(scopes, default_scopes=None)[source]

Create a copy of these credentials with the specified scopes.

Parameters:

scopes (Sequencestr) – The list of scopes to attach to the current credentials.

Raises:

NotImplementedError – If the credentials’ scopes can not be changed. This can be avoided by checking requires_scopes before calling this method.

with_token_uri(token_uri)[source]

Returns a copy of these credentials with a modified token uri.

Parameters:

token_uri (str) – The uri to use for fetching/exchanging tokens

Returns:

A new credentials instance.

Return type:

google.auth.credentials.Credentials

with_universe_domain(universe_domain)[source]

Returns a copy of these credentials with a modified universe domain.

Parameters:

universe_domain (str) – The universe domain to use

Returns:

A new credentials instance.

Return type:

google.auth.credentials.Credentials

token

The bearer token that can be used in HTTP headers to make authenticated requests.

Type:

str

expiry

When the token expires and is no longer valid. If this is None, the token is assumed to never expire.

Type:

Optionaldatetime

classmethod from_info(info, **kwargs)[source]

Creates an Identity Pool Credentials instance from parsed external account info.

Parameters:
  • info (Mappingstr, str) – The Identity Pool external account info in Google format.

  • kwargs – Additional arguments to pass to the constructor.

Returns:

The constructed

credentials.

Return type:

google.auth.identity_pool.Credentials

Raises:

ValueError – For invalid parameters.

classmethod from_file(filename, **kwargs)[source]

Creates an IdentityPool Credentials instance from an external account json file.

Parameters:
  • filename (str) – The path to the IdentityPool external account json file.

  • kwargs – Additional arguments to pass to the constructor.

Returns:

The constructed

credentials.

Return type:

google.auth.identity_pool.Credentials