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.
- payload (
Mapping
[str
,str
]) – The JWT payload. - header (
Mapping
[str
,str
]) – Additional JWT header payload. - 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.
Parameters: token ( Union
[str
,bytes
]) – the encoded JWT.Returns: The decoded JWT header. Return type: Mapping
decode
(token, certs=None, verify=True, audience=None)[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.
Returns: The deserialized JSON payload in the JWT.
Return type: Raises: ValueError
– if any verification checks failed.
- class
Credentials
(signer, issuer, subject, audience, additional_claims=None, token_lifetime=3600, quota_project_id=None)[source]¶ Bases: google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
Credentials that use a JWT as the bearer token.
See AlsoDecode and verify the signature of a Cognito JSON Web TokenWhat are some alternatives to JSON? - StackShareUnderstanding the Limitations of JSON and Exploring Faster Alternatives for Improved Application PerformanceThese 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 aSigner instance:
credentials = 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: 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 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: google.oauth2.credentials.Credentials
refresh
(request)[source]¶Refreshes the access token.
Parameters: request ( Any
) – Unused.
sign_bytes
(message)[source]¶Signs the given message.
Parameters: message (bytes) – The message to sign. Returns: The message’s cryptographic signature. Return type: bytes
signer
¶The signer used to sign bytes.
Type: google.auth.crypt.Signer
apply
(headers, token=None)[source]¶Apply the token to the authentication header.
Parameters:
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:
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.
quota_project_id
¶Project to use for quota and billing purposes.
valid
¶Checks the validity of the credentials.
This is True if the credentials have a
token
and the tokenis not expired.
- class
OnDemandCredentials
(signer, issuer, subject, additional_claims=None, token_lifetime=3600, max_cache_size=10, quota_project_id=None)[source]¶ Bases: google.auth.credentials.Signing, google.auth.credentials.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: ValueError
– 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: google.oauth2.credentials.Credentials
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.
Parameters:
sign_bytes
(message)[source]¶Signs the given message.
Parameters: message (bytes) – The message to sign. Returns: The message’s cryptographic signature. Return type: bytes
signer
¶The signer used to sign bytes.
Type: google.auth.crypt.Signer
apply
(headers, token=None)¶Apply the token to the authentication header.
Parameters:
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.
quota_project_id
¶Project to use for quota and billing purposes.