JSON Web Token (JWT)

The jwt Module implements the JSON Web Token standard. A JSON Web Token is represented by a JWT object, related utility classes and functions are available in this module too.

Classes

class jwcrypto.jwt.JWT(header=None, claims=None, jwt=None, key=None, algs=None, default_claims=None, check_claims=None, expected_type=None)

Bases: object

JSON Web token object

This object represent a generic token.

Creates a JWT object.

Parameters:
  • header – A dict or a JSON string with the JWT Header data.

  • claims – A dict or a string with the JWT Claims data.

  • jwt – a ‘raw’ JWT token

  • key – A (jwcrypto.jwk.JWK) key to deserialize the token. A (jwcrypto.jwk.JWKSet) can also be used.

  • algs – An optional list of allowed algorithms

  • default_claims – An optional dict with default values for registered claims. A None value for NumericDate type claims will cause generation according to system time. Only the values from RFC 7519 - 4.1 are evaluated.

  • check_claims – An optional dict of claims that must be present in the token, if the value is not None the claim must match exactly.

  • expected_type – An optional string that defines what kind of token to expect when validating a deserialized token. Supported values: “JWS” or “JWE” If left to None the code will try to detect what the expected type is based on other parameters like ‘algs’ and will default to JWS if no hints are found. It has no effect on token creation.

Note: either the header,claims or jwt,key parameters should be provided as a deserialization operation (which occurs if the jwt is provided) will wipe any header or claim provided by setting those obtained from the deserialization of the jwt token.

Note: if check_claims is not provided the ‘exp’ and ‘nbf’ claims are checked if they are set on the token but not enforced if not set. Any other RFC 7519 registered claims are checked only for format conformance.

deserialize(jwt, key=None)

Deserialize a JWT token.

NOTE: Destroys any current status and tries to import the raw token provided.

Parameters:
classmethod from_jose_token(token)

Creates a JWT object from a serialized JWT token.

Parameters:

token – A string with the json or compat representation of the token.

Raises:

InvalidJWEData or InvalidJWSObject – if the raw object is an invalid JWT token.

Returns:

A JWT token

Return type:

JWT

make_encrypted_token(key)

Encrypts the payload.

Creates a JWE token with the header as the JWE protected header and the claims as the plaintext. See (jwcrypto.jwe.JWE) for details on the exceptions that may be raised.

Parameters:

key – A (jwcrypto.jwk.JWK) key.

make_signed_token(key)

Signs the payload.

Creates a JWS token with the header as the JWS protected header and the claims as the payload. See (jwcrypto.jws.JWS) for details on the exceptions that may be raised.

Parameters:

key – A (jwcrypto.jwk.JWK) key.

serialize(compact=True)

Serializes the object into a JWS token.

Parameters:

compact(boolean) – must be True.

Note: the compact parameter is provided for general compatibility with the serialize() functions of jwcrypto.jws.JWS and jwcrypto.jwe.JWE so that these objects can all be used interchangeably. However the only valid JWT representation is the compact representation.

Returns:

A json formatted string or a compact representation string

Return type:

str

validate(key)

Validate a JWT token that was deserialized w/o providing a key

Parameters:

key – A (jwcrypto.jwk.JWK) verification or decryption key, or a (jwcrypto.jwk.JWKSet) that contains a key indexed by the ‘kid’ header.

Variables

jwcrypto.jwt.JWTClaimsRegistry = {'aud': 'Audience', 'exp': 'Expiration Time', 'iat': 'Issued At', 'iss': 'Issuer', 'jti': 'JWT ID', 'nbf': 'Not Before', 'sub': 'Subject'}

Registry of RFC 7519 defined claims

jwcrypto.jwt.JWT_expect_type = True

This module parameter can disable the use of the expectation feature that has been introduced to fix CVE-2022-3102. This knob has been added as a workaround for applications that can’t be immediately refactored to deal with the change in behavior but it is considered deprecated and will be removed in a future release.

Examples

Create a symmetric key::
>>> from jwcrypto import jwt, jwk
>>> key = jwk.JWK(generate='oct', size=256)
>>> key.export()  
'{"k":"...","kty":"oct"}'
Create a signed token with the generated key::
>>> Token = jwt.JWT(header={"alg": "HS256"},
...                 claims={"info": "I'm a signed token"})
>>> Token.make_signed_token(key)
>>> Token.serialize()       
'eyJhbGciOiJIUzI1NiJ9.eyJpbmZvIjoiSSdtIGEgc2lnbmVkIHRva2VuIn0...'
Further encrypt the token with the same key::
>>> Etoken = jwt.JWT(header={"alg": "A256KW", "enc": "A256CBC-HS512"},
...                  claims=Token.serialize())
>>> Etoken.make_encrypted_token(key)
>>> Etoken.serialize()
'eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIn0...'
Now decrypt and verify::
>>> from jwcrypto import jwt, jwk
>>> k = {"k": "Wal4ZHCBsml0Al_Y8faoNTKsXCkw8eefKXYFuwTBOpA", "kty": "oct"}
>>> key = jwk.JWK(**k)
>>> e = 'eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIn0.ST5RmjqDLj696xo7YFTFuKUhcd3naCrm6yMjBM3cqWiFD6U8j2JIsbclsF7ryNg8Ktmt1kQJRKavV6DaTl1T840tP3sIs1qz.wSxVhZH5GyzbJnPBAUMdzQ.6uiVYwrRBzAm7Uge9rEUjExPWGbgerF177A7tMuQurJAqBhgk3_5vee5DRH84kHSapFOxcEuDdMBEQLI7V2E0F57-d01TFStHzwtgtSmeZRQ6JSIL5XlgJouwHfSxn9Z_TGl5xxq4TksORHED1vnRA.5jPyPWanJVqlOohApEbHmxi3JHp1MXbmvQe2_dVd8FI'
>>> ET = jwt.JWT(key=key, jwt=e, expected_type="JWE")
>>> ST = jwt.JWT(key=key, jwt=ET.claims)
>>> ST.claims
'{"info":"I\'m a signed token"}'