PyJWT
JSON Web Token implementation for Python that encodes, decodes, and verifies signatures and claims.
Official Documentation ↗v2. Check the official docs for the latest API surface.Installation
pip install pyjwtMethods
No methods match this filter.
JSON Web Token implementation for Python that encodes, decodes, and verifies signatures and claims.
Overview
PyJWT implements the JWS compact serialization for Python: encode signs a claim payload into the three-part token string, and decode verifies the signature and registered claims before returning the payload.
HS256 covers symmetric deployments; RS256 and friends verify with public keys, matching OAuth and OIDC issuers. The exception hierarchy separates expiry from invalidity so applications can respond with precise semantics instead of blanket 401s.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
jwt.encode— Signs a payload into a compact JWS token; put exp, iat, and sub claims in the payload.jwt.decode— Verifies signature and time claims, then returns the payload; algorithms is mandatory.exception hierarchy— Typed failures distinguishing expiry, audience, issuer, and malformed tokens for precise handling.RS256 (asymmetric)— Asymmetric mode: services verify with the public key while only the issuer holds the private key.
Usage Notes
- Always pass algorithms, audience, and issuer on decode; defaults are not a security policy.
- Keep access token lifetimes minutes-scale and use refresh tokens for longer sessions.
- Standardize UTC datetimes in claims; mixing naive and aware values breaks exp math.
Common Pitfalls
- Calling decode without algorithms raises an error, and bypassing it invites algorithm confusion.
- Forgetting audience verification lets tokens from one API be replayed against another.
- Putting sensitive data in the payload: it is base64, readable by anyone holding the token.
FAQ
- Why must algorithms be explicit?
- Specifying algorithms prevents algorithm confusion, where an attacker swaps RS256 for HS256 and the verifier signs data with the public key as an HMAC secret. Pin the exact algorithms you issue.
- How do I verify exp automatically?
- decode verifies exp and nbf by default when present in the payload. Use the options dict to control individual claims, and pass audience and issuer arguments to verify those claims too.
- Where do I store tokens on the client?
- Prefer short-lived access tokens kept in memory with refresh tokens in hardened storage. PyJWT is server-side only: it cannot mitigate XSS once a token leaks, so keep lifetimes short and rotate.
Report a problem with this API docOpens a pre-filled issue on GitHub.