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
Dow Jones Futures: CPI Inflation Report Due After S&P 500 Breaks Key Level
FHA 203K Rehab Loan- What You need to Know
Whas Golf Card
The Blackening Showtimes Near Century Aurora And Xd
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Housing near Juneau, WI - craigslist
Gomoviesmalayalam
craigslist: kenosha-racine jobs, apartments, for sale, services, community, and events
Voorraad - Foodtrailers
Www Thechristhospital Billpay
83600 Block Of 11Th Street East Palmdale Ca
Tugboat Information
Does Pappadeaux Pay Weekly
PGA of America leaving Palm Beach Gardens for Frisco, Texas
Lima Funeral Home Bristol Ri Obituaries
Bitlife Tyrone's
Charter Spectrum Store
Odfl4Us Driver Login
Invitation Homes plans to spend $1 billion buying houses in an already overheated market. Here's its presentation to investors setting out its playbook.
Heart and Vascular Clinic in Monticello - North Memorial Health
Touchless Car Wash Schaumburg
Craigslist St. Cloud Minnesota
Munis Self Service Brockton
Rogue Lineage Uber Titles
Harrison County Wv Arrests This Week
Die 8 Rollen einer Führungskraft
Cowboy Pozisyon
Mawal Gameroom Download
Insidious 5 Showtimes Near Cinemark Southland Center And Xd
Barbie Showtimes Near Lucas Cinemas Albertville
Rugged Gentleman Barber Shop Martinsburg Wv
Perry Inhofe Mansion
Abga Gestation Calculator
October 19 Sunset
2015 Chevrolet Silverado 1500 for sale - Houston, TX - craigslist
The Complete Guide To The Infamous "imskirby Incident"
Puffco Peak 3 Red Flashes
2020 Can-Am DS 90 X Vs 2020 Honda TRX90X: By the Numbers
South Bend Tribune Online
Atom Tickets – Buy Movie Tickets, Invite Friends, Skip Lines
Torrid Rn Number Lookup
Setx Sports
Tom Kha Gai Soup Near Me
Dontrell Nelson - 2016 - Football - University of Memphis Athletics
Sea Guini Dress Code
Bama Rush Is Back! Here Are the 15 Most Outrageous Sorority Houses on the Row
Lux Funeral New Braunfels
Sleep Outfitters Springhurst
Diablo Spawns Blox Fruits
Kenmore Coldspot Model 106 Light Bulb Replacement
Heisenberg Breaking Bad Wiki
Emmi-Sellers
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.