google.oauth2.service_account module

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

This module implements the JWT Profile for OAuth 2.0 Authorization Grants as defined by RFC 7523 with particular support for how this RFC is implemented in Google’s infrastructure. Google refers to these credentials as Service Accounts.

Service accounts are used for server-to-server communication, such as interactions between a web application server and a Google service. The service account belongs to your application instead of to an individual end user. In contrast to other OAuth 2.0 profiles, no users are involved and your application “acts” as the service account.

Typically an application uses a service account when the application uses Google APIs to work with its own data rather than a user’s data. For example, an application that uses Google Cloud Datastore for data persistence would use a service account to authenticate its calls to the Google Cloud Datastore API. However, an application that needs to access a user’s Drive documents would use the normal OAuth 2.0 profile.

Additionally, Google Apps domain administrators can grant service accounts domain-wide delegation authority to access user data on behalf of users in the domain.

This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used in place of the usual authorization token returned during the standard OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as the acquired access token is used as the bearer token when making requests using these credentials.

This profile differs from normal OAuth 2.0 profile because no user consent step is required. The use of the private key allows this profile to assert identity directly.

This profile also differs from the google.auth.jwt authentication because the JWT credentials use the JWT directly as the bearer token. This profile instead only uses the JWT to obtain an OAuth 2.0 access token. The obtained OAuth 2.0 access token is used as the bearer token.

Domain-wide delegation

Domain-wide delegation allows a service account to access user data on behalf of any user in a Google Apps domain without consent from the user. For example, an application that uses the Google Calendar API to add events to the calendars of all users in a Google Apps domain would use a service account to access the Google Calendar API on behalf of users.

The Google Apps administrator must explicitly authorize the service account to do this. This authorization step is referred to as “delegating domain-wide authority” to a service account.

You can use domain-wise delegation by creating a set of credentials with a specific subject using with_subject().

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: Signing, Scoped, CredentialsWithQuotaProject, CredentialsWithTokenUri

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

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.

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

property service_account_email

The service account email.

property project_id

Project ID associated with this credential.

property requires_scopes

Checks if the credentials requires scopes.

Returns:

True if there are no scopes set otherwise False.

Return type:

bool

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

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

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.

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

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.

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 quota_project_id

Project to use for quota and billing purposes.

property scopes

the credentials’ current set of scopes.

Type:

Sequencestr

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.

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: Signing, CredentialsWithQuotaProject, CredentialsWithTokenUri

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

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.

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

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

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.

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.

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

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

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