Repository navigation
v0.2.0
The library grew from a JWT string type into a way to declare tokens as models.
0.1.1 shipped JWTStr and JWTConstraints; everything else here is new.
Full documentation: [pydantic-jwt.dmi03.com](https://pydantic-jwt.dmi03.com)
from pydantic_jwt import ConfigDict, Exp, JWTModel, after, uuid
class AccessToken(JWTModel):
model_config = ConfigDict(
algorithm="HS256",
encoding_key=SECRET,
decoding_key=SECRET,
)
sub: str
exp: Exp = after(minutes=15)
jti: str = uuid()
raw = str(AccessToken(sub="user-42")) # issue
token = AccessToken.from_token(raw) # read back, verifiedAdded
JWTModel— a Pydantic model that is also a JWT. One class issues tokens
(generate(),str(),.jwt_str) and validates incoming ones
(from_token(), or by validating a token string into the field), with the
signature verified through PyJWT. The algorithm comes from your configuration
and never from the token header, so a forgedalgcannot influence
verification.- Claim markers —
Exp,NbfandIatvalidate against the current clock
(with an optionalleewayfor clock skew);IssClaimandAudClaimvalidate
against an expected issuer and audience. All are plainAnnotatedmetadata,
so they compose with anything else Pydantic can do to a field, andClaimcan
be subclassed for your own. - Field defaults —
after(),at()anduuid()forexp,nbfand
jti, evaluated per instance so every token gets fresh values. ConfigDict— Pydantic's config extended withalgorithm,
encoding_key,decoding_keyandrequire_keys.- Per-call keys —
from_token()acceptsdecoding_key,algorithmand
require_keysoverriding the config, and reads the same values from the
validation context, for keys that are only known at request time. - OpenAPI support — a token model reports itself as
{"type": "string", "format": "jwt"}with its claims listed in the
description. - Documentation site — guides, a full API reference,
[security notes](https://pydantic-jwt.dmi03.com/guide/security/) and a
complete [FastAPI example](https://pydantic-jwt.dmi03.com/integrations/fastapi/)
with bearer authentication, refresh tokens and scopes.
Removed
JWTConstraints. Constraints are now expressed as claim markers on a
JWTModelfield, which validate the parsed claim instead of the raw string.
JWTStris unchanged and still does structural validation only.
Fixed
- The validation context is now forwarded through
from_token(), so
context={"validate_claims": False}works for tokens validated from a token
string and not only from a dict.
Requirements
Python 3.10+, Pydantic 2.10+, PyJWT.
pip install pydantic-jwt