google.oauth2.service_account_async module

Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0

NOTE: This file adds asynchronous refresh methods to both credentials classes, and therefore async/await syntax is required when calling this method when using service account credentials with asynchronous functionality. Otherwise, all other methods are inherited from the regular service account credentials file google.oauth2.service_account

class Credentials(signer, service_account_email, token_uri, scopes=None, default_scopes=None, subject=None, project_id=None, quota_project_id=None, additional_claims=None, always_use_jwt_access=False, universe_domain='googleapis.com', trust_boundary=None)[source]

Bases: Credentials, Scoped, Credentials

Service account credentials

Usually, you’ll create these credentials with one of the helper constructors. To create credentials using a Google service account private key JSON file:

credentials = _service_account_async.Credentials.from_service_account_file(
    'service-account.json')

Or if you already have the service account file loaded:

service_account_info = json.load(open('service_account.json'))
credentials = _service_account_async.Credentials.from_service_account_info(
    service_account_info)

Both helper methods pass on arguments to the constructor, so you can specify additional scopes and a subject if necessary:

credentials = _service_account_async.Credentials.from_service_account_file(
    'service-account.json',
    scopes=['email'],
    subject='user@example.com')

The credentials are considered immutable. If you want to modify the scopes or the subject used for delegation, use with_scopes() or with_subject():

scoped_credentials = credentials.with_scopes(['email'])
delegated_credentials = credentials.with_subject(subject)

To add a quota project, use with_quota_project():

credentials = credentials.with_quota_project('myproject-123')
Parameters:
  • signer (google.auth.crypt.Signer) – The signer used to sign JWTs.

  • service_account_email (str) – The service account’s email.

  • scopes (Sequencestr) – User-defined scopes to request during the authorization grant.

  • default_scopes (Sequencestr) – Default scopes passed by a Google client library. Use ‘scopes’ for user-defined scopes.

  • token_uri (str) – The OAuth 2.0 Token URI.

  • 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 (Optionalstr) – The project ID used for quota and billing.

  • additional_claims (Mappingstr, str) – Any additional claims for the JWT assertion used in the authorization grant.

  • always_use_jwt_access (Optionalbool) – Whether self signed JWT should be always used.

  • universe_domain (str) – The universe domain. The default universe domain is googleapis.com. For default value self signed jwt is used for token refresh.

  • trust_boundary (str) – String representation of trust boundary meta.

Note

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

async 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.

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.

async 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.

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

Creates a Credentials instance from a service account json file.

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

  • kwargs – Additional arguments to pass to the constructor.

Returns:

The constructed

credentials.

Return type:

google.auth.service_account.Credentials

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

Creates a Credentials instance from parsed service account info.

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

  • kwargs – Additional arguments to pass to the constructor.

Returns:

The constructed

credentials.

Return type:

google.auth.service_account.Credentials

Raises:

ValueError – If the info is not in the expected format.

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 project_id

Project ID associated with this credential.

property quota_project_id

Project to use for quota and billing purposes.

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

The service account email.

sign_bytes(message)[source]

Signs the given message.

Parameters:

message (bytes) – The message to sign.

Returns:

The message’s cryptographic signature.

Return type:

bytes

property signer

The signer used to sign bytes.

Type:

google.auth.crypt.Signer

property signer_email

An email address that identifies the signer.

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_always_use_jwt_access(always_use_jwt_access)[source]

Create a copy of these credentials with the specified always_use_jwt_access value.

Parameters:

always_use_jwt_access (bool) – Whether always use self signed JWT or not.

Returns:

A new credentials

instance.

Return type:

google.auth.service_account.Credentials

Raises:

google.auth.exceptions.InvalidValue – If the universe domain is not default and always_use_jwt_access is False.

with_claims(additional_claims)[source]

Returns a copy of these credentials with modified claims.

Parameters:

additional_claims (Mappingstr, str) – Any additional claims for the JWT payload. This will be merged with the current additional claims.

Returns:

A new credentials

instance.

Return type:

google.auth.service_account.Credentials

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_subject(subject)[source]

Create a copy of these credentials with the specified subject.

Parameters:

subject (str) – The subject claim.

Returns:

A new credentials

instance.

Return type:

google.auth.service_account.Credentials

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

class IDTokenCredentials(signer, service_account_email, token_uri, target_audience, additional_claims=None, quota_project_id=None, universe_domain='googleapis.com')[source]

Bases: IDTokenCredentials, Signing, Credentials

Open ID Connect ID Token-based service account credentials.

These credentials are largely similar to Credentials, but instead of using an OAuth 2.0 Access Token as the bearer token, they use an Open ID Connect ID Token as the bearer token. These credentials are useful when communicating to services that require ID Tokens and can not accept access tokens.

Usually, you’ll create these credentials with one of the helper constructors. To create credentials using a Google service account private key JSON file:

credentials = (
    _service_account_async.IDTokenCredentials.from_service_account_file(
        'service-account.json'))

Or if you already have the service account file loaded:

service_account_info = json.load(open('service_account.json'))
credentials = (
    _service_account_async.IDTokenCredentials.from_service_account_info(
        service_account_info))

Both helper methods pass on arguments to the constructor, so you can specify additional scopes and a subject if necessary:

credentials = (
    _service_account_async.IDTokenCredentials.from_service_account_file(
        'service-account.json',
        scopes=['email'],
        subject='user@example.com'))

The credentials are considered immutable. If you want to modify the scopes or the subject used for delegation, use with_scopes() or with_subject():

scoped_credentials = credentials.with_scopes(['email'])
delegated_credentials = credentials.with_subject(subject)
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.

  • target_audience (str) – The intended audience for these credentials, used when requesting the ID Token. The ID Token’s aud claim will be set to this string.

  • additional_claims (Mappingstr, str) – Any additional claims for the JWT assertion used in the authorization grant.

  • quota_project_id (Optionalstr) – The project ID used for quota and billing.

  • universe_domain (str) – The universe domain. The default universe domain is googleapis.com. For default value IAM ID token endponint is used for token refresh. Note that iam.serviceAccountTokenCreator role is required to use the IAM endpoint.

Note

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

async 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.

apply(headers, token=None)

Apply the token to the authentication header.

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

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

async before_request(request, method, url, headers)

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 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.

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

Creates a credentials instance from a service account json file.

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

  • kwargs – Additional arguments to pass to the constructor.

Returns:

The constructed

credentials.

Return type:

google.auth.service_account.IDTokenCredentials

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

Creates a credentials instance from parsed service account info.

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

  • kwargs – Additional arguments to pass to the constructor.

Returns:

The constructed

credentials.

Return type:

google.auth.service_account.IDTokenCredentials

Raises:

ValueError – If the info is not in the expected format.

property quota_project_id

Project to use for quota and billing purposes.

property service_account_email

The service account email.

sign_bytes(message)[source]

Signs the given message.

Parameters:

message (bytes) – The message to sign.

Returns:

The message’s cryptographic signature.

Return type:

bytes

property signer

The signer used to sign bytes.

Type:

google.auth.crypt.Signer

property signer_email

An email address that identifies the signer.

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_target_audience(target_audience)[source]

Create a copy of these credentials with the specified target audience.

Parameters:
  • target_audience (str) – The intended audience for these credentials,

  • Token. (used when requesting the ID) –

Returns:

A new credentials

instance.

Return type:

google.auth.service_account.IDTokenCredentials

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

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