liveBook · Manning

PyJWT

As explained in Secure APIs

PyJWT is a Python library for encoding and decoding JSON Web Tokens.

PyJWT is a Python library for encoding and decoding JSON Web Tokens. It provides a simple interface for issuing signed tokens and validating their signatures and claims. section 8.2 section 8.3

Use PyJWT to:

  • Create a payload containing claims such as issuer, subject, audience, issue time, and expiration. section 8.2
  • Issue an HS256 token with a shared signing key or a PS256 token with a private key. section 8.2
  • Validate tokens by restricting algorithms and checking the expected audience and issuer; expired tokens are also rejected. section 8.3

Issuing and validating an API token

Build a payload with an issuer, user subject, API audience, current UTC issue time, and one-hour expiration. Call jwt.encode(payload=payload, key="password", algorithm="HS256") to issue the token. Later, call jwt.decode(jwt=token, key="password", algorithms=["HS256"], audience="https://apithreats.com/api", issuer="https://auth.apithreats.com") to recover the payload. A successful call returns claims; an invalid token raises an exception. section 8.2 section 8.3

Listing 8.3 Example JWT payload
# file: ch08/jwt_generator_pyjwt_hs256.py
from datetime import datetime, timezone, timedelta

now = datetime.now(timezone.utc)
payload = {
    "iss": "https://auth.apithreats.com",
    "sub": "23456543",
    "aud": "https://apithreats.com/api",
    "iat": now,
    "exp": (now + timedelta(hours=1))
}

Inspect a complete payload example showing issuer, subject, audience, issue time, and expiration before signing it with PyJWT. section 8.2

How Secure APIs covers it

How deep it goes
Explains payload construction, symmetric and asymmetric signing, decode parameters, claim checks, and validation failures without detailing library internals.
Examples
Demonstrates HS256 and PS256 issuance, payload dictionaries, generated tokens, and HS256 or PS256 validation functions.
What it assumes
Assumes basic Python and JWT familiarity while demonstrating payload claims, signing keys, and validation from concrete examples.
What you can do after
Build it from scratch by issuing and validating JWTs with explicit algorithms, keys, audiences, issuers, and expiration handling.
How it connects
Connects JWTs with claims, signing algorithms, shared keys, private and public keys, audience validation, and issuer validation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secure APIs. The section links point to the parts of the book it draws on.