google.auth.jwt module — google-auth 1.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 (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:

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 (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:

Mapping [ str, str ]

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 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:
  • info (Mapping [ str, 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:

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_email

An email address that identifies the signer.

Type:Optional [ str ]
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:
  • headers (Mapping) – The HTTP request headers.
  • token (Optional [ str ]) – 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.
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:
  • info (Mapping [ str, 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:

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:
  • 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
signer_email

An email address that identifies the signer.

Type:Optional [ str ]
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 (Optional [ str ]) – If specified, overrides the current accesstoken.
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.

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

FAQs

Why Google authentication failed? ›

My Google Authenticator codes don't work

It may be because the time isn't correctly synced on your Google Authenticator app. On the next screen, the app confirms the time has been synced. You should be able to sign in.

How can I verify a Google authentication API access token? ›

You can inspect a valid (not expired or revoked) ID token by using the tokeninfo endpoint. Replace ID_TOKEN with the valid, unexpired ID token. This command returns something similar to the following example: See more code actions.

What is the Google JWT file? ›

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.

What is GoogleAuth? ›

google-auth is the Google authentication library for Python. This library provides the ability to authenticate to Google APIs using various methods. It also provides integration with several HTTP libraries. Support for Google Application Default Credentials . Support for signing and verifying JWTs .

How do I fix Google authorization failed? ›

Resolution
  1. Open Google Authenticator app on your mobile.
  2. At the top-right corner, click on the action (three-dot) icon.
  3. Click on Settings from the drop-down.
  4. Choose Time Correction for Codes.
  5. Select Sync Now.
  6. Check whether the Two Factor Authentication is working or not.
  7. Open Settings on your mobile.

How do I fix authentication failed? ›

If you trust the WiFi account and you want to get connected, try these six steps:
  1. Forget the network. ...
  2. Check your password. ...
  3. Refresh your device. ...
  4. Change your network from DHCP to Static. ...
  5. Restart your router. ...
  6. Head back to factory settings.

How do I verify my JWT access token? ›

We must send the access token to the OneLogin OIDC app's introspection endpoint to validate the token. If the token is valid, the introspection endpoint will respond with an HTTP 200 response code. The body of the response will also contain an augmented version of the original JWT token's payload.

Why is my Google Authenticator token invalid? ›

Ensure your device's time is set correctly, as apps like Google Authenticator rely on accurate time settings to generate valid tokens. For Android: Go to Settings > System > Date & Time > enable Automatic date & time. For iPhone: Go to Settings > General > Date & Time > enable Set Automatically.

How do I know if my auth token is valid? ›

You can validate your tokens locally by parsing the token, verifying the token signature, and validating the claims that are stored in the token. Parse the tokens. The JSON Web Token (JWT) is a standard way of securely passing information. It consists of three main parts: Header, Payload, and Signature.

Why avoid JWT? ›

With JWT, the biggest problem is there are no reliable ways to log out users. The logout is fully controlled by the client, the server side can do nothing about it. It can just expect the client will forget about the token, that's it. This is dangerous from a security perspective.

How to use JWT to authenticate? ›

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.

Is JWT mandatory? ›

The JWT specification defines seven reserved claims that are not required, but are recommended to allow interoperability with third-party applications. These are: iss (issuer): Issuer of the JWT.

What are Google Authenticator codes? ›

Google Authenticator app generates a six-digit code for you to enter when you log in. The code changes about every minute. Once you have set up the connection with ACF's site, every time that you log out of your ACF account you will need to use Google Authenticator to regain access when you login again.

Who uses Google Authenticator? ›

Who uses Google Authenticator?
CompanyWebsiteCountry
Cognizant Technology Solutions Corpcognizant.comUnited States
Infosys Ltdinfosys.comIndia
Wipro Ltdwipro.comIndia
Fujitsu Ltdfujitsu.comJapan
1 more row

Is the Google authentication API free? ›

For the basic information like name, email and user ID is free for it is within the free tier of Oauth. However, there might be some indirect costs like free tier limits which have a limit on the number of requests you can make. Exceeding these limits might require a paid plan.

Why is the Google Authenticator not working? ›

The codes that Authy or Google Authenticator is generating aren't working when I enter them. This might be because the time on your Google Authenticator or Authy app is not synced correctly. To make sure that you have the correct time: Go to the main menu on the Google Authenticator app.

How do I fix authentication failed in Gmail? ›

To fix this problem you need to do the following steps:
  1. Make sure that you have entered the correct password.
  2. Check if you have enabled the two-factor authentication. ...
  3. Enable less secure apps access in your Google account settings. ...
  4. Log out from the other Google accounts.
Jul 9, 2024

Why does it keep saying authorization failed? ›

You may encounter an error of “Authorization failed”. The most common cause of this error is incorrect information entered during a login attempt on Android-based terminals.

How do I get Google Authenticator to work again? ›

If you have your backup key saved, follow these steps to recover the access:
  1. Download the Google Authenticator app on your device and open it.
  2. Find and press the "+" sign. ...
  3. You will be prompted with options to either "Scan a QR code" or "Enter a setup key." Choose "Enter a setup key."

Top Articles
Virginia Car Insurance Laws: Do You Need Car Insurance in Virginia?
How to get a loan in Germany as an Expat | Expats.de
Chs.mywork
Kreme Delite Menu
Mountain Dew Bennington Pontoon
Goodbye Horses: The Many Lives of Q Lazzarus
Faint Citrine Lost Ark
A Complete Guide To Major Scales
Cumberland Maryland Craigslist
Mikayla Campino Video Twitter: Unveiling the Viral Sensation and Its Impact on Social Media
Craigslistdaytona
Alaska Bücher in der richtigen Reihenfolge
Walgreens On Nacogdoches And O'connor
Blue Beetle Showtimes Near Regal Swamp Fox
Arboristsite Forum Chainsaw
Craigslist Blackshear Ga
Immortal Ink Waxahachie
How Much Is Tay Ks Bail
Jalapeno Grill Ponca City Menu
U Break It Near Me
Accuweather Mold Count
Wgu Academy Phone Number
Optum Urgent Care - Nutley Photos
Air Quality Index Endicott Ny
Gazette Obituary Colorado Springs
Caring Hearts For Canines Aberdeen Nc
Apartments / Housing For Rent near Lake Placid, FL - craigslist
Plost Dental
What Equals 16
Sound Of Freedom Showtimes Near Movie Tavern Brookfield Square
Maine Racer Swap And Sell
Shoe Station Store Locator
Amazing Lash Bay Colony
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
Wasmo Link Telegram
Covalen hiring Ai Annotator - Dutch , Finnish, Japanese , Polish , Swedish in Dublin, County Dublin, Ireland | LinkedIn
Space Marine 2 Error Code 4: Connection Lost [Solved]
Gets Less Antsy Crossword Clue
Rage Of Harrogath Bugged
Winco Money Order Hours
Emulating Web Browser in a Dedicated Intermediary Box
Carroll White Remc Outage Map
Lucifer Morningstar Wiki
Panolian Batesville Ms Obituaries 2022
Grand Valley State University Library Hours
About Us
Wzzm Weather Forecast
Rovert Wrestling
Www Extramovies Com
Invitation Quinceanera Espanol
San Pedro Sula To Miami Google Flights
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 6050

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.