JSON Web Tokens
Provides support for creating (encoding) and verifying (decoding) JWTs,especially JWTs generated and consumed by Google infrastructure.
See rfc7519 for more details on JWTs.
To encode a JWT use encode():
from google.auth import cryptfrom google.auth import jwtsigner = crypt.Signer(private_key)payload = {'some': 'payload'}encoded = jwt.encode(signer, payload)
To decode a JWT and verify claims use decode():
claims = jwt.decode(encoded, certs=public_certs)
You can also skip verification:
claims = jwt.decode(encoded, verify=False)
- encode(signer, payload, header=None, key_id=None)[source]¶
Make a signed JWT.
- Parameters:
signer (google.auth.crypt.Signer) – The signer used to sign the JWT.
key_id (str) – The key id to add to the JWT header. If thesigner has a key id it will be used as the default. If this isspecified it will override the signer’s key id.
- Returns:
The encoded JWT.
- Return type:
- decode_header(token)[source]¶
Return the decoded header of a token.
No verification is done. This is useful to extract the key id fromthe header in order to acquire the appropriate certificate to verifythe token.
- decode(token, certs=None, verify=True, audience=None, clock_skew_in_seconds=0)[source]¶
Decode and verify a JWT.
- Parameters:
token (str) – The encoded JWT.
certs (
Union
str
,bytes
,Mapping
str
,Union
str
,bytes
) – Thecertificate used to validate the JWT signature. If bytes or string,it must the the public key certificate in PEM format. If a mapping,it must be a mapping of key IDs to public key certificates in PEMformat. The mapping must contain the same key ID that’s specifiedin the token’s header.verify (bool) – Whether to perform signature and claim validation.Verification is done by default.
audience (str or list) – The audience claim, ‘aud’, that this JWT shouldcontain. Or a list of audience claims. If None then the JWT’s ‘aud’parameter is not verified.
clock_skew_in_seconds (int) – The clock skew used for iat and expvalidation.
- Returns:
The deserialized JSON payload in the JWT.
- Return type:
- Raises:
google.auth.exceptions.InvalidValue – if value validation failed.
google.auth.exceptions.MalformedError – if schema validation failed.
- class Credentials(signer, issuer, subject, audience, additional_claims=None, token_lifetime=3600, quota_project_id=None)[source]¶
Bases:
Signing
,CredentialsWithQuotaProject
Credentials that use a JWT as the bearer token.
These credentials require an “audience” claim. This claim identifies theintended recipient of the bearer token.
The constructor arguments determine the claims for the JWT that issent with requests. Usually, you’ll construct these credentials withone of the helper constructors as shown in the next section.
To create JWT credentials using a Google service account private keyJSON file:
audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher'credentials = jwt.Credentials.from_service_account_file( 'service-account.json', audience=audience)
If you already have the service account file loaded and parsed:
service_account_info = json.load(open('service_account.json'))credentials = jwt.Credentials.from_service_account_info( service_account_info, audience=audience)
Both helper methods pass on arguments to the constructor, so you canspecify the JWT claims:
credentials = jwt.Credentials.from_service_account_file( 'service-account.json', audience=audience, additional_claims={'meta': 'data'})
You can also construct the credentials directly if you have a
Signer
instance:See AlsoJSON Web Token ClaimsGmail authentication errorgoogle-auth — google-auth 1.30.0 documentationWhy you should not use JWT for authenticationcredentials = jwt.Credentials( signer, issuer='your-issuer', subject='your-subject', audience=audience)
The claims are considered immutable. If you want to modify the claims,you can easily create another instance using with_claims():
new_audience = ( 'https://pubsub.googleapis.com/google.pubsub.v1.Subscriber')new_credentials = credentials.with_claims(audience=new_audience)
- Parameters:
signer (google.auth.crypt.Signer) – The signer used to sign JWTs.
issuer (str) – The iss claim.
subject (str) – The sub claim.
audience (str) – the aud claim. The intended audience for thecredentials.
additional_claims (
Mapping
str
,str
) –Any
additional claims forthe JWT payload.token_lifetime (int) – The amount of time in seconds forwhich the token is valid. Defaults to 1 hour.
quota_project_id (
Optional
str
) – The project ID used for quotaand billing.
- classmethod from_service_account_info(info, **kwargs)[source]¶
Creates an Credentials instance from a dictionary.
- Parameters:
- Returns:
The constructed credentials.
- Return type:
google.auth.jwt.Credentials
- Raises:
google.auth.exceptions.MalformedError – 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 filein Google format.
- 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.jwt.Credentials
- classmethod from_signing_credentials(credentials, audience, **kwargs)[source]¶
Creates a new google.auth.jwt.Credentials instance from anexisting
google.auth.credentials.Signing
instance.The new instance will use the same signer as the existing instance andwill use the existing instance’s signer email as the issuer andsubject by default.
Example:
svc_creds = service_account.Credentials.from_service_account_file( 'service_account.json')audience = ( 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher')jwt_creds = jwt.Credentials.from_signing_credentials( svc_creds, audience=audience)
- Parameters:
credentials (google.auth.credentials.Signing) – The credentials touse to construct the new credentials.
audience (str) – the aud claim. The intended audience for thecredentials.
kwargs – Additional arguments to pass to the constructor.
- Returns:
A new Credentials instance.
- Return type:
google.auth.jwt.Credentials
- with_claims(issuer=None, subject=None, audience=None, additional_claims=None)[source]¶
Returns a copy of these credentials with modified claims.
- Parameters:
issuer (str) – The iss claim. If unspecified the current issuerclaim will be used.
subject (str) – The sub claim. If unspecified the current subjectclaim will be used.
audience (str) – the aud claim. If unspecified the currentaudience claim will be used.
additional_claims (
Mapping
str
,str
) –Any
additional claims forthe JWT payload. This will be merged with the currentadditional claims.
- Returns:
A new credentials instance.
- Return type:
google.auth.jwt.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 andbilling purposes
- Returns:
A new credentials instance.
- Return type:
- sign_bytes(message)[source]¶
Signs the given message.
- property signer¶
The signer used to sign bytes.
- property additional_claims¶
Additional claims the JWT object was created with.
- apply(headers, token=None)[source]¶
Apply the token to the authentication header.
- before_request(request, method, url, headers)[source]¶
Performs credential-specific before request logic.
Refreshes the credentials if necessary, then calls apply() toapply the token to the authentication header.
- Parameters:
request (google.auth.transport.Request) – The object used to makeHTTP requests.
method (str) – The request’s HTTP method or the RPC method beinginvoked.
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 becauseCredentials with expiry set to None is considered to neverexpire.
Deprecated since version v2.24.0: Prefer checking token_state instead.
- property quota_project_id¶
Project to use for quota and billing purposes.
- 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 tokenis 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 makeauthenticated requests.
- Type:
- class OnDemandCredentials(signer, issuer, subject, additional_claims=None, token_lifetime=3600, max_cache_size=10, quota_project_id=None)[source]¶
Bases:
Signing
,CredentialsWithQuotaProject
On-demand JWT credentials.
Like Credentials, this class uses a JWT as the bearer token forauthentication. However, this class does not require the audience atconstruction time. Instead, it will generate a new token on-demand foreach request using the request URI as the audience. It caches tokensso that multiple requests to the same URI do not incur the overheadof generating a new token every time.
This behavior is especially useful for gRPC clients. A gRPC service mayhave multiple audience and gRPC clients may not know all of the audiencesrequired for accessing a particular service. With these credentials,no knowledge of the audiences is required ahead of time.
- Parameters:
signer (google.auth.crypt.Signer) – The signer used to sign JWTs.
issuer (str) – The iss claim.
subject (str) – The sub claim.
additional_claims (
Mapping
str
,str
) –Any
additional claims forthe JWT payload.token_lifetime (int) – The amount of time in seconds forwhich the token is valid. Defaults to 1 hour.
max_cache_size (int) – The maximum number of JWT tokens to keep incache. Tokens are cached using
cachetools.LRUCache
.quota_project_id (
Optional
str
) – The project ID used for quotaand billing.
- classmethod from_service_account_info(info, **kwargs)[source]¶
Creates an OnDemandCredentials instance from a dictionary.
- Parameters:
- Returns:
The constructed credentials.
- Return type:
google.auth.jwt.OnDemandCredentials
- Raises:
google.auth.exceptions.MalformedError – If the info is not in the expected format.
- classmethod from_service_account_file(filename, **kwargs)[source]¶
Creates an OnDemandCredentials instance from a service account .jsonfile in Google format.
- 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.jwt.OnDemandCredentials
- classmethod from_signing_credentials(credentials, **kwargs)[source]¶
Creates a new google.auth.jwt.OnDemandCredentials instancefrom an existing
google.auth.credentials.Signing
instance.The new instance will use the same signer as the existing instance andwill use the existing instance’s signer email as the issuer andsubject by default.
Example:
svc_creds = service_account.Credentials.from_service_account_file( 'service_account.json')jwt_creds = jwt.OnDemandCredentials.from_signing_credentials( svc_creds)
- Parameters:
credentials (google.auth.credentials.Signing) – The credentials touse to construct the new credentials.
kwargs – Additional arguments to pass to the constructor.
- Returns:
A new Credentials instance.
- Return type:
google.auth.jwt.Credentials
- with_claims(issuer=None, subject=None, additional_claims=None)[source]¶
Returns a copy of these credentials with modified claims.
- Parameters:
issuer (str) – The iss claim. If unspecified the current issuerclaim will be used.
subject (str) – The sub claim. If unspecified the current subjectclaim will be used.
additional_claims (
Mapping
str
,str
) –Any
additional claims forthe JWT payload. This will be merged with the currentadditional claims.
- Returns:
A new credentials instance.
- Return type:
google.auth.jwt.OnDemandCredentials
- 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 andbilling purposes
- Returns:
A new credentials instance.
- Return type:
- property valid¶
Checks the validity of the credentials.
These credentials are always valid because it generates tokens ondemand.
- refresh(request)[source]¶
Raises an exception, these credentials can not be directlyrefreshed.
- Parameters:
request (
Any
) – Unused.- Raises:
google.auth.RefreshError –
- before_request(request, method, url, headers)[source]¶
Performs credential-specific before request logic.
- sign_bytes(message)[source]¶
Signs the given message.
- property signer¶
The signer used to sign bytes.
- apply(headers, token=None)¶
Apply the token to the authentication header.
- property expired¶
Checks if the credentials are expired.
Note that credentials can be invalid but not expired becauseCredentials with expiry set to None is considered to neverexpire.
Deprecated since version v2.24.0: Prefer checking token_state instead.
- property quota_project_id¶
Project to use for quota and billing purposes.
- property token_state¶
See :obj:`TokenState
- property universe_domain¶
The universe domain value.
- token¶
The bearer token that can be used in HTTP headers to makeauthenticated requests.
- Type: