JSON Web Token

This section contains the generic Python implementation of RFC7519.

Guide on JWT

JSON Web Token (JWT) is structured by JSON Web Signature or :specs/rfc7516 with certain payload claims. The JWT implementation in Authlib has all built-in algorithms via JSON Web Algorithms, it can also load private/public keys of JSON Web Key:

>>> from authlib.specs.rfc7519 import jwt
>>> header = {'alg': 'RS256'}
>>> payload = {'iss': 'Authlib', 'sub': '123', ...}
>>> key = read_file('private.pem')
>>> s = jwt.encode(header, payload, key)
>>> claims = jwt.decode(s, read_file('public.pem'))
>>> print(claims)
{'iss': 'Authlib', 'sub': '123', ...}
>>> print(claims.header)
{'alg': 'RS256', 'typ': 'JWT'}
>>> claims.validate()

The imported jwt is a instance of JWT. It has all supported JWS algorithms, and it can handle JWK automatically. When JWT.encode() a payload, JWT will check payload claims for security, if you really want to expose them, you can always turn if off via check=False.

Important

JWT payload with JWS is not encrypted, it is just signed. Anyone can extract the payload without any private or public keys. Adding sensitive data like passwords, social security numbers in JWT payload is not safe if you are going to send them in a non-secure connection.

You can also use JWT with JWE which is encrypted. But this feature is not mature, documentation is not provided yet.

JWT Payload Claims Validation

JWT.decode() accepts 3 claims related parameters: claims_cls, claims_option and claims_params. The default claims_cls is JWTClaims. The decode method equals:

>>> JWTClaims(payload, header, options=claims_options, params=claims_params)

Claims validation is actually handled by JWTClaims.validate(), which validate payload claims with claims_option and claims_params. For standard JWTClaims, claims_params value is not used, but it is used in IDToken.

Here is an example of claims_option:

{
    "iss": {
        "essential": True,
        "values": ["https://example.com", "https://example.org"]
    },
    "sub": {
        "essential": True
        "value": "248289761001"
    },
    "jti": {
        "validate": validate_jti
    }
}

It is a dict configuration, the option key is the name of a claim.

  • essential: this value is REQUIRED.
  • values: claim value can be any one in the values list.
  • value: claim value MUST be the same value.
  • validate: a function to validate the claim value.

API Reference

class authlib.specs.rfc7519.JWT(algorithms=None, private_headers=None)
check_sensitive_data(payload)

Check if payload contains sensitive information.

encode(header, payload, key, check=True)

Encode a JWT with the given header, payload and key.

Parameters:
  • header – A dict of JWS header
  • payload – A dict to be encoded
  • key – key used to sign the signature
  • check – check if sensitive data in payload
Returns:

JWT

decode(s, key, claims_cls=None, claims_options=None, claims_params=None)

Decode the JWS with the given key. This is similar with verify(), except that it will raise BadSignatureError when signature doesn’t match.

Parameters:
  • s – text of JWT
  • key – key used to verify the signature
  • claims_cls – class to be used for JWT claims
  • claims_optionsoptions parameters for claims_cls
  • claims_paramsparams parameters for claims_cls
Returns:

claims_cls instance

Raise:

BadSignatureError

class authlib.specs.rfc7519.JWTClaims(payload, header, options=None, params=None)

Payload claims for JWT, which contains a validate interface.

Parameters:
  • payload – the payload dict of JWT
  • header – the header dict of JWT
  • options – validate options
  • params – other params

An example on options parameter, the format is inspired by OpenID Connect Claims:

{
    "iss": {
        "essential": True,
        "values": ["https://example.com", "https://example.org"]
    },
    "sub": {
        "essential": True
        "value": "248289761001"
    },
    "jti": {
        "validate": validate_jti
    }
}
validate(now=None, leeway=0)

Validate everything in claims payload.

validate_iss()

The “iss” (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The “iss” value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.

validate_sub()

The “sub” (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The “sub” value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.

validate_aud()

The “aud” (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the “aud” claim when this claim is present, then the JWT MUST be rejected. In the general case, the “aud” value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the “aud” value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

validate_exp(now, leeway)

The “exp” (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the “exp” claim requires that the current date/time MUST be before the expiration date/time listed in the “exp” claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

validate_nbf(now, leeway)

The “nbf” (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the “nbf” claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the “nbf” claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

validate_iat(now, leeway)

The “iat” (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

validate_jti()

The “jti” (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The “jti” claim can be used to prevent the JWT from being replayed. The “jti” value is a case- sensitive string. Use of this claim is OPTIONAL.