google.auth.jwt module¶
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 crypt
from google.auth import jwt
signer = 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 the signer has a key id it will be used as the default. If this is specified 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 from the header in order to acquire the appropriate certificate to verify the 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
] ] ]) – The certificate 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 PEM format. The mapping must contain the same key ID that’s specified in 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 should contain. 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.
These credentials require an “audience” claim. This claim identifies the intended recipient of the bearer token.
The constructor arguments determine the claims for the JWT that is sent with requests. Usually, you’ll construct these credentials with one of the helper constructors as shown in the next section.
To create JWT credentials using a Google service account private key JSON 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 can specify 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: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 the credentials.
- additional_claims (
Mapping
[str
,str
]) –Any
additional claims for the JWT payload. - token_lifetime (int) – The amount of time in seconds for which the token is valid. Defaults to 1 hour.
- quota_project_id (
Optional
[str
]) – The project ID used for quota and billing.
-
classmethod
from_service_account_info
(info, **kwargs)[source]¶ Creates an Credentials instance from a dictionary.
Parameters: Returns: The constructed credentials.
Return type: 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 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:
-
classmethod
from_signing_credentials
(credentials, audience, **kwargs)[source]¶ Creates a new
google.auth.jwt.Credentials
instance from an existinggoogle.auth.credentials.Signing
instance.The new instance will use the same signer as the existing instance and will use the existing instance’s signer email as the issuer and subject 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 to use to construct the new credentials.
- audience (str) – the aud claim. The intended audience for the credentials.
- kwargs – Additional arguments to pass to the constructor.
Returns: A new Credentials instance.
Return type:
-
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 issuer claim will be used.
- subject (str) – The sub claim. If unspecified the current subject claim will be used.
- audience (str) – the aud claim. If unspecified the current audience claim will be used.
- additional_claims (
Mapping
[str
,str
]) –Any
additional claims for the JWT payload. This will be merged with the current additional claims.
Returns: A new credentials instance.
Return type:
-
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.oauth2.credentials.Credentials
-
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
-
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.
-
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.
-
quota_project_id
¶ Project to use for quota and billing purposes.
-
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 for authentication. However, this class does not require the audience at construction time. Instead, it will generate a new token on-demand for each request using the request URI as the audience. It caches tokens so that multiple requests to the same URI do not incur the overhead of generating a new token every time.This behavior is especially useful for gRPC clients. A gRPC service may have multiple audience and gRPC clients may not know all of the audiences required 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 for the JWT payload. - token_lifetime (int) – The amount of time in seconds for which the token is valid. Defaults to 1 hour.
- max_cache_size (int) – The maximum number of JWT tokens to keep in
cache. Tokens are cached using
cachetools.LRUCache
. - quota_project_id (
Optional
[str
]) – The project ID used for quota and billing.
-
classmethod
from_service_account_info
(info, **kwargs)[source]¶ Creates an OnDemandCredentials instance from a dictionary.
Parameters: Returns: The constructed credentials.
Return type: 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 .json file 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:
-
classmethod
from_signing_credentials
(credentials, **kwargs)[source]¶ Creates a new
google.auth.jwt.OnDemandCredentials
instance from an existinggoogle.auth.credentials.Signing
instance.The new instance will use the same signer as the existing instance and will use the existing instance’s signer email as the issuer and subject 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 to use to construct the new credentials.
- kwargs – Additional arguments to pass to the constructor.
Returns: A new Credentials instance.
Return type:
-
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 issuer claim will be used.
- subject (str) – The sub claim. If unspecified the current subject claim will be used.
- additional_claims (
Mapping
[str
,str
]) –Any
additional claims for the JWT payload. This will be merged with the current additional claims.
Returns: A new credentials instance.
Return type:
-
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.oauth2.credentials.Credentials
-
valid
¶ Checks the validity of the credentials.
These credentials are always valid because it generates tokens on demand.
-
refresh
(request)[source]¶ Raises an exception, these credentials can not be directly refreshed.
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 because Credentials with
expiry
set to None is considered to never expire.
-
quota_project_id
¶ Project to use for quota and billing purposes.