google.auth.jwt module — google-auth 2.30.0 documentation (2024)

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 (Mappingstr, str) – The JWT payload.

  • header (Mappingstr, 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:

bytes

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 (Unionstr, bytes) – the encoded JWT.

Returns:

The decoded JWT header.

Return type:

Mapping

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 (Unionstr, bytes, Mappingstr, Unionstr, 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:

Mappingstr, str

Raises:
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 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 (Mappingstr, 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 (Optionalstr) – The project ID used for quotaand billing.

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

Creates an Credentials instance from a dictionary.

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

  • kwargs – Additional arguments to pass to the constructor.

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 (Mappingstr, 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.auth.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

property signer_email

An email address that identifies the signer.

Type:

Optionalstr

property signer

The signer used to sign bytes.

Type:

google.auth.crypt.Signer

property additional_claims

Additional claims the JWT object was created with.

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

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:

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 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 (Mappingstr, 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 (Optionalstr) – The project ID used for quotaand billing.

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

Creates an OnDemandCredentials instance from a dictionary.

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

  • kwargs – Additional arguments to pass to the constructor.

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 (Mappingstr, 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.auth.credentials.Credentials

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.

Parameters:
  • request (Any) – Unused. JWT credentials do not need to make anHTTP request to refresh.

  • method (str) – The request’s HTTP method.

  • url (str) – The request’s URI. This is used as the audience claimwhen generating the JWT.

  • headers (Mapping) – The request’s headers.

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_email

An email address that identifies the signer.

Type:

Optionalstr

property signer

The signer used to sign bytes.

Type:

google.auth.crypt.Signer

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

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:

str

expiry

When the token expires and is no longer valid.If this is None, the token is assumed to never expire.

Type:

Optionaldatetime

google.auth.jwt module — google-auth 2.30.0 documentation (2024)
Top Articles
Two-step verification process | CIBC
How Timesheet Hours Are Calculated – When I Work Help Center
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 6227

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.