API Reference
- jwt.encode(payload, key, algorithm='HS256', headers=None, json_encoder=None) str
Encode the
payloadas JSON Web Token.- Parameters:
payload (dict[str, Any]) – JWT claims, e.g.
dict(iss=..., aud=..., sub=...)key (str or bytes or PyJWK or
jwt.algorithms.AllowedPrivateKeys) –a key suitable for the chosen algorithm:
for asymmetric algorithms: PEM-formatted private key, a multiline string
for symmetric algorithms: plain string, sufficiently long for security
algorithm (str or None) – algorithm to sign the token with, e.g.
"ES256". Ifheadersincludesalg, it will be preferred to this parameter. Ifkeyis aPyJWKobject, by default the key algorithm will be used.headers (dict[str, Any] or None) – additional JWT header fields, e.g.
dict(kid="my-key-id").json_encoder (json.JSONEncoder or None) – custom JSON encoder for
payloadandheaders
- Return type:
- Returns:
a JSON Web Token
- Raises:
TypeError – if
payloadis not adict
- jwt.decode(jwt, key='', algorithms=None, options=None, audience=None, issuer=None, leeway=0) dict[str, Any]
Verify the
jwttoken signature and return the token claims.- Parameters:
key (str or bytes or PyJWK or
jwt.algorithms.AllowedPublicKeys) – the key suitable for the allowed algorithmalgorithms (Sequence[str] or None) –
allowed algorithms, e.g.
["ES256"]Ifkeyis aPyJWKobject, allowed algorithms will default to the key algorithm.Warning
Do not compute the
algorithmsparameter based on thealgfrom the token itself, or on any other data that an attacker may be able to influence, as that might expose you to various vulnerabilities (see RFC 8725 §2.1). Instead, either hard-code a fixed value foralgorithms, or configure it in the same place you configure thekey. Make sure not to mix symmetric and asymmetric algorithms that interpret thekeyin different ways (e.g. HS* and RS*).options (jwt.types.Options) – extended decoding and validation options Refer to
jwt.types.Optionsfor more information.audience (str or Iterable[str] or None) – optional, the value for
verify_audchecksubject (str or None) – optional, the value for
verify_subcheckissuer (str or Container[str] or None) – optional, the value for
verify_isscheckleeway (float or datetime.timedelta) – a time margin in seconds for the expiration check
- Return type:
- Returns:
the JWT claims
- jwt.decode_complete(jwt, key='', algorithms=None, options=None, verify=None, detached_payload=None, audience=None, issuer=None, subject=None, leeway=0) dict[str, Any]
Identical to
jwt.decodeexcept for return value which is a dictionary containing the token header (JOSE Header), the token payload (JWT Payload), and token signature (JWT Signature) on the keys “header”, “payload”, and “signature” respectively.- Parameters:
key (str or bytes or PyJWK or
jwt.algorithms.AllowedPublicKeys) – the key suitable for the allowed algorithmalgorithms (Sequence[str] or None) –
allowed algorithms, e.g.
["ES256"]Warning
Do not compute the
algorithmsparameter based on thealgfrom the token itself, or on any other data that an attacker may be able to influence, as that might expose you to various vulnerabilities (see RFC 8725 §2.1). Instead, either hard-code a fixed value foralgorithms, or configure it in the same place you configure thekey. Make sure not to mix symmetric and asymmetric algorithms that interpret thekeyin different ways (e.g. HS* and RS*).options (jwt.types.Options) – extended decoding and validation options Refer to
jwt.types.Optionsfor more information.audience (str or Iterable[str] or None) – optional, the value for
verify_audcheckissuer (str or Container[str] or None) – optional, the value for
verify_isscheckleeway (float or datetime.timedelta) – a time margin in seconds for the expiration check
- Return type:
- Returns:
Decoded JWT with the JOSE Header on the key
header, the JWS Payload on the keypayload, and the JWS Signature on the keysignature.
- class jwt.PyJWT(options: Options | None = None)
- decode(jwt: str | bytes, key: RSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey | PyJWK | str | bytes = '', algorithms: Sequence[str] | None = None, options: Options | None = None, verify: bool | None = None, detached_payload: bytes | None = None, audience: str | Iterable[str] | None = None, subject: str | None = None, issuer: str | Container[str] | None = None, leeway: float | timedelta = 0, **kwargs: Any) dict[str, Any]
Verify the
jwttoken signature and return the token claims.- Parameters:
key (str or bytes or PyJWK or
jwt.algorithms.AllowedPublicKeys) – the key suitable for the allowed algorithmalgorithms (Sequence[str] or None) –
allowed algorithms, e.g.
["ES256"]Ifkeyis aPyJWKobject, allowed algorithms will default to the key algorithm.Warning
Do not compute the
algorithmsparameter based on thealgfrom the token itself, or on any other data that an attacker may be able to influence, as that might expose you to various vulnerabilities (see RFC 8725 §2.1). Instead, either hard-code a fixed value foralgorithms, or configure it in the same place you configure thekey. Make sure not to mix symmetric and asymmetric algorithms that interpret thekeyin different ways (e.g. HS* and RS*).options (jwt.types.Options) – extended decoding and validation options Refer to
jwt.types.Optionsfor more information.audience (str or Iterable[str] or None) – optional, the value for
verify_audchecksubject (str or None) – optional, the value for
verify_subcheckissuer (str or Container[str] or None) – optional, the value for
verify_isscheckleeway (float or datetime.timedelta) – a time margin in seconds for the expiration check
- Return type:
- Returns:
the JWT claims
- decode_complete(jwt: str | bytes, key: RSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey | PyJWK | str | bytes = '', algorithms: Sequence[str] | None = None, options: Options | None = None, verify: bool | None = None, detached_payload: bytes | None = None, audience: str | Iterable[str] | None = None, issuer: str | Container[str] | None = None, subject: str | None = None, leeway: float | timedelta = 0, **kwargs: Any) dict[str, Any]
Identical to
jwt.decodeexcept for return value which is a dictionary containing the token header (JOSE Header), the token payload (JWT Payload), and token signature (JWT Signature) on the keys “header”, “payload”, and “signature” respectively.- Parameters:
key (str or bytes or PyJWK or
jwt.algorithms.AllowedPublicKeys) – the key suitable for the allowed algorithmalgorithms (Sequence[str] or None) –
allowed algorithms, e.g.
["ES256"]Warning
Do not compute the
algorithmsparameter based on thealgfrom the token itself, or on any other data that an attacker may be able to influence, as that might expose you to various vulnerabilities (see RFC 8725 §2.1). Instead, either hard-code a fixed value foralgorithms, or configure it in the same place you configure thekey. Make sure not to mix symmetric and asymmetric algorithms that interpret thekeyin different ways (e.g. HS* and RS*).options (jwt.types.Options) – extended decoding and validation options Refer to
jwt.types.Optionsfor more information.audience (str or Iterable[str] or None) – optional, the value for
verify_audcheckissuer (str or Container[str] or None) – optional, the value for
verify_isscheckleeway (float or datetime.timedelta) – a time margin in seconds for the expiration check
- Return type:
- Returns:
Decoded JWT with the JOSE Header on the key
header, the JWS Payload on the keypayload, and the JWS Signature on the keysignature.
- encode(payload: dict[str, ~typing.Any], key: ~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey | ~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey | ~cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey | ~cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey | ~jwt.api_jwk.PyJWK | str | bytes, algorithm: str | None = <object object>, headers: dict[str, ~typing.Any] | None = None, json_encoder: type[~json.JSONEncoder] | None = None, sort_headers: bool = True) str
Encode the
payloadas JSON Web Token.- Parameters:
payload (dict[str, Any]) – JWT claims, e.g.
dict(iss=..., aud=..., sub=...)key (str or bytes or PyJWK or
jwt.algorithms.AllowedPrivateKeys) –a key suitable for the chosen algorithm:
for asymmetric algorithms: PEM-formatted private key, a multiline string
for symmetric algorithms: plain string, sufficiently long for security
algorithm (str or None) – algorithm to sign the token with, e.g.
"ES256". Ifheadersincludesalg, it will be preferred to this parameter. Ifkeyis aPyJWKobject, by default the key algorithm will be used.headers (dict[str, Any] or None) – additional JWT header fields, e.g.
dict(kid="my-key-id").json_encoder (json.JSONEncoder or None) – custom JSON encoder for
payloadandheaders
- Return type:
- Returns:
a JSON Web Token
- Raises:
TypeError – if
payloadis not adict
- class jwt.PyJWK(jwk_data: dict[str, Any], algorithm: str | None = None)
A class that represents a JSON Web Key.
- Parameters:
- Raises:
InvalidKeyError – If the key type (
kty) is not found or unsupported, or if the curve (crv) is not found or unsupported.MissingCryptographyError – If the algorithm requires
cryptographyto be installed and it is not available.PyJWKError – If unable to find an algorithm for the key.
- static from_dict(obj: dict[str, Any], algorithm: str | None = None) PyJWK
Creates a
PyJWKobject from a JSON-like dictionary.
- class jwt.PyJWKClient(uri: str, cache_keys: bool = False, max_cached_keys: int = 16, cache_jwk_set: bool = True, lifespan: float = 300, headers: dict[str, Any] | None = None, timeout: float = 30, ssl_context: SSLContext | None = None)
A client for retrieving signing keys from a JWKS endpoint.
PyJWKClientuses a two-tier caching system to avoid unnecessary network requests:Tier 1 — JWK Set cache (enabled by default): Caches the entire JSON Web Key Set response from the endpoint. Controlled by:
cache_jwk_set: Set toTrue(the default) to enable this cache. When enabled, the JWK Set is fetched from the network only when the cache is empty or expired.lifespan: Time in seconds before the cached JWK Set expires. Defaults to300(5 minutes). Must be greater than 0.
Tier 2 — Signing key cache (disabled by default): Caches individual signing keys (looked up by
kid) using an LRU cache with no time-based expiration. Keys are evicted only when the cache reaches its maximum size. Controlled by:cache_keys: Set toTrueto enable this cache. Defaults toFalse.max_cached_keys: Maximum number of signing keys to keep in the LRU cache. Defaults to16.
- Parameters:
uri (str) – The URL of the JWKS endpoint.
cache_keys (bool) – Enable the per-key LRU cache (Tier 2).
max_cached_keys (int) – Max entries in the signing key LRU cache.
cache_jwk_set (bool) – Enable the JWK Set response cache (Tier 1).
lifespan (float) – TTL in seconds for the JWK Set cache.
headers (dict or None) – Optional HTTP headers to include in requests.
timeout (float) – HTTP request timeout in seconds.
ssl_context (ssl.SSLContext or None) – Optional SSL context for the request.
- fetch_data() Any
Fetch the JWK Set from the JWKS endpoint.
Makes an HTTP request to the configured
uriand returns the parsed JSON response. If the JWK Set cache is enabled, the response is stored in the cache.- Returns:
The parsed JWK Set as a dictionary.
- Raises:
PyJWKClientConnectionError – If the HTTP request fails.
- get_jwk_set(refresh: bool = False) PyJWKSet
Return the JWK Set, using the cache when available.
- Parameters:
refresh (bool) – Force a fresh fetch from the endpoint, bypassing the cache.
- Returns:
The JWK Set.
- Return type:
- Raises:
PyJWKClientError – If the endpoint does not return a JSON object.
- get_signing_key(kid: str) PyJWK
Return the signing key matching the given
kid.If no match is found in the current JWK Set, the set is refreshed from the endpoint and the lookup is retried once.
- Parameters:
kid (str) – The key ID to look up.
- Returns:
The matching signing key.
- Return type:
- Raises:
PyJWKClientError – If no matching key is found after refreshing.
- get_signing_key_from_jwt(token: str | bytes) PyJWK
Return the signing key for a JWT by reading its
kidheader.Extracts the
kidfrom the token’s unverified header and delegates toget_signing_key().
- get_signing_keys(refresh: bool = False) list[PyJWK]
Return all signing keys from the JWK Set.
Filters the JWK Set to keys whose
useis"sig"(or unspecified) and that have akid.- Parameters:
refresh (bool) – Force a fresh fetch from the endpoint, bypassing the cache.
- Returns:
A list of signing keys.
- Return type:
- Raises:
PyJWKClientError – If no signing keys are found.
Note
TODO: Finish documenting PyJWS class
- class jwt.api_jws.PyJWS(algorithms: Sequence[str] | None = None, options: SigOptions | None = None)
- get_algorithm_by_name(alg_name: str) Algorithm
For a given string name, return the matching Algorithm object.
Example usage: >>> jws_obj = PyJWS() >>> jws_obj.get_algorithm_by_name(“RS256”)
- get_unverified_header(jwt: str | bytes) dict[str, Any]
Returns back the JWT header parameters as a dict
Note: The signature is not verified so the header parameters should not be fully trusted until signature verification is complete
Algorithms
- class jwt.algorithms.Algorithm
The interface for an algorithm used to sign and verify tokens.
- check_crypto_key_type(key: DHPublicKey | DSAPublicKey | RSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey | X25519PublicKey | X448PublicKey | DHPrivateKey | Ed25519PrivateKey | Ed448PrivateKey | RSAPrivateKey | DSAPrivateKey | EllipticCurvePrivateKey | X25519PrivateKey | X448PrivateKey) None
Check that the key belongs to the right cryptographic family.
Note that this method only works when
cryptographyis installed.- Parameters:
key (
PublicKeyTypes|PrivateKeyTypes) – Potentially a cryptography key- Raises:
ValueError – if
cryptographyis not installed, or this method is called by a non-cryptography algorithmInvalidKeyError – if the key doesn’t match the expected key classes
- check_key_length(key: Any) str | None
Return a warning message if the key is below the minimum recommended length for this algorithm, or None if adequate.
- compute_hash_digest(bytestr: bytes) bytes
Compute a hash digest using the specified algorithm’s hash algorithm.
If there is no hash algorithm, raises a NotImplementedError.
- abstractmethod static from_jwk(jwk: str | dict[str, Any]) Any
Deserializes a given key from JWK back into a key object
- abstractmethod prepare_key(key: Any) Any
Performs necessary validation and conversions on the key and returns the key value in the proper format for sign() and verify().
- abstractmethod sign(msg: bytes, key: Any) bytes
Returns a digital signature for the specified message using the specified key value.
- jwt.algorithms.AllowedPrivateKeys
Type alias for allowed
cryptographyprivate keys (requirescryptographyto be installed)alias of
RSAPrivateKey|EllipticCurvePrivateKey|Ed25519PrivateKey|Ed448PrivateKey
- jwt.algorithms.AllowedPublicKeys
Type alias for allowed
cryptographypublic keys (requirescryptographyto be installed)alias of
RSAPublicKey|EllipticCurvePublicKey|Ed25519PublicKey|Ed448PublicKey
Types
- class jwt.types.SigOptions
Options for PyJWS class (TypedDict). Note that this is a smaller set of options than for
jwt.decode().- enforce_minimum_key_length: bool
Default:
False. Raisejwt.exceptions.InvalidKeyErrorinstead of warning when keys are below minimum recommended length.
- class jwt.types.Options
Options for
jwt.decode()andjwt.decode_complete()(TypedDict).Warning
Some claims, such as
exp,iat,jti,nbf, andsub, will only be verified if present. Please refer to the documentation below for which ones, and make sure to include them in therequireparam if you want to make sure that they are always present (and therefore always verified ifverify_{claim} = Truefor that claim).- enforce_minimum_key_length: bool
Default:
False. Raisejwt.exceptions.InvalidKeyErrorinstead of warning when keys are below minimum recommended length.
- require: list[str]
Default:
[]. List of claims that must be present. Example:require=["exp", "iat", "nbf"]. Only verifies that the claims exists. Does not verify that the claims are valid.
- strict_aud: bool
Default:
False. (requiresverify_aud=True) Check that theaudclaim is a single value (not a list), and matchesaudienceexactly.
- verify_exp: bool
Default:
verify_signature. Check thatexp(expiration) claim value is in the future (if present in payload).
- verify_iat: bool
Default:
verify_signature. Check thatiat(issued at) claim value is an integer (if present in payload).
- verify_jti: bool
Default:
verify_signature. Check thatjti(JWT ID) claim is a string (if present in payload).
Warnings
- exception jwt.warnings.InsecureKeyLengthWarning
Bases:
UserWarningWarning emitted when a cryptographic key is shorter than the minimum recommended length. See Key Length Validation for details.
- exception jwt.warnings.RemovedInPyjwt3Warning
Bases:
DeprecationWarningWarning for features that will be removed in PyJWT 3.
Exceptions
- exception jwt.exceptions.DecodeError
Bases:
InvalidTokenErrorRaised when a token cannot be decoded because it failed validation
- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.ExpiredSignatureError
Bases:
InvalidTokenErrorRaised when a token’s
expclaim indicates that it has expired- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.ImmatureSignatureError
Bases:
InvalidTokenErrorRaised when a token’s
nbforiatclaims represent a time in the future- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidAlgorithmError
Bases:
InvalidTokenErrorRaised when the specified algorithm is not recognized by PyJWT
- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidAudienceError
Bases:
InvalidTokenErrorRaised when a token’s
audclaim does not match one of the expected audience values- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidIssuedAtError
Bases:
InvalidTokenErrorRaised when a token’s
iatclaim is non-numeric- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidIssuerError
Bases:
InvalidTokenErrorRaised when a token’s
issclaim does not match the expected issuer- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidJTIError
Bases:
InvalidTokenErrorRaised when a token’s
jticlaim is not a string- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidKeyError
Bases:
PyJWTErrorRaised when the specified key is not in the proper format
- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidSignatureError
Bases:
DecodeErrorRaised when a token’s signature doesn’t match the one provided as part of the token.
- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidSubjectError
Bases:
InvalidTokenErrorRaised when a token’s
subclaim is not a string or doesn’t match the expectedsubject- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.InvalidTokenError
Bases:
PyJWTErrorBase exception when
decode()fails on a token- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.MissingCryptographyError
Bases:
PyJWKErrorRaised if the algorithm requires
cryptographyto be installed and it is not available.- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.MissingRequiredClaimError(claim: str)
Bases:
InvalidTokenErrorRaised when a claim that is required to be present is not contained in the claimset
- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.PyJWKClientConnectionError
Bases:
PyJWKClientError- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.PyJWKClientError
Bases:
PyJWTError- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.PyJWKError
Bases:
PyJWTError- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception jwt.exceptions.PyJWKSetError
Bases:
PyJWTError- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.