Nox
Download

Standard library

nox.jwt

JSON Web Tokens signed with HMAC-SHA-256 (HS256).

Text
import nox.jwt
from nox.jwt import JwtError

Capability: none registered (pure Nox over nox.crypto, nox.base64 and nox.json); not on the freestanding allow-list.

Functions#

Function Description
sign(payload_json, secret) returns header.payload.signature for the JSON text payload_json, signed with secret
verify(token, secret) checks the signature (in constant time) and returns the payload JSON text; raises JwtError for a malformed token, a wrong algorithm or a bad signature
verify_claims(token, secret, now_s, leeway_s) verify, then enforces the time claims against now_s (Unix seconds) with leeway_s seconds of clock skew: exp (expired when now ≥ exp), nbf (not valid yet when now < nbf) and iat (issued in the future). Absent claims are skipped; a non-numeric one or a non-object payload raises JwtError
verify_now(token, secret, leeway_s) verify_claims with the current wall clock

The token is three Base64url parts separated by dots. verify does not interpret claims: use verify_claims/verify_now for exp, nbf and iat; aud, iss and the rest are yours to enforce — parse the returned payload with nox.json.

Nox
import nox.jwt
from nox.jwt import JwtError

tok: str = nox.jwt.sign("{\"sub\":\"ada\"}", "secret")
print(tok.count("."), nox.jwt.verify(tok, "secret"))
try:
    nox.jwt.verify(tok, "wrong-secret")
except JwtError as e:
    print("rejected")
Output
2 {"sub":"ada"}
rejected

Notes#

  • Only HS256 is implemented; tokens that declare another algorithm (including none) are rejected.
  • Use a secret of at least 32 random bytes (nox.crypto.secure_random_hex(32)) and keep it out of source control.