Skip to Content
oxcrypto

JWT

Encode JSON Web Tokens as JWS and validate their registered claims.

from secrets import token_bytes

from oxcrypto.jose import jwt
from oxcrypto.jose.jws import JWS

secret = token_bytes(32)
token = jwt.encode({"sub": "alice", "aud": "api", "exp": 2_000_000_000}, secret, algorithm=JWS.HS256)
claims = jwt.decode(token, secret, algorithm=JWS.HS256, audience="api")
assert claims["sub"] == "alice"

encode(claims, key, *, algorithm, header=None) serializes claims with json.dumps and signs it with the JWS selector, adding typ: JWT. decode verifies the JWS with the same algorithm checks, then validates claims:

  • exp and nbf are checked against now (default: the current time in seconds) with leeway seconds of tolerance. A token is expired once now >= exp + leeway.
  • aud must contain audience when the token has an aud claim, and a token with aud is rejected when no audience is given.
  • iss and sub must equal issuer and subject when those are given.
  • Every name in required must be present.

Failed claims raise ValueError; a bad signature or wrong algorithm raises InvalidTag.