Skip to main content

jwt-pydantic

JWT claim sets are becoming more complex and harder to manage. Writing validators for these claims checks is time consuming.

This package uses the power of Pydantic models, to make life a bit easier.

We have also included a Starlette middleware, which can be easily used in FastAPI, as shown here.

Example

Let's say our JWT token has the claims set below:

claims = {
    "firstname": "David",
    "surname": "Bowie",
    "best_album": "Hunky Dory"
}

We can use jwt-pydantic to simplify the generation and verification of such tokens. First we declare the Pydantic model, by subclassing JWTPydantic:

from jwt_pydantic import JWTPydantic

class MyJWT(JWTPydantic):
    firstname: str
    surname: str
    best_album: str

To generate a new JWT token, using the claims above, we do the following:

token = MyJWT.new_token(claims=claims, key="SECRET_KEY")

We can then verify this token easily as follows

MyJWT.verify_token(token, key="SECRET_KEY")

We can also return the decoded JWT token as our Pydantic model, to be used elsewhere:

decoded_jwt = MyJWT(token, key="SECRET_KEY")
print(decoded_jwt.firstname)  # David

FastAPI Middleware

It is also easy to declare a new JWTPydantic model and use this in middleware, as shown below.

# main.py
from fastapi import FastAPI
from jwt_pydantic import JWTPydantic, JWTPydanticMiddleware

SECRET_KEY = "mykey"

class MyJWT(JWTPydantic):
    foo: int

app = FastAPI()
app.add_middleware(
    JWTPydanticMiddleware,
    header_name="jwt",
    jwt_pydantic_model=MyJWT,
    jwt_key=SECRET_KEY,
)

@app.get("/")
def homepage():
    return "Hello world"

We can run this code easily using uvicorn (uvicorn main:app --reload), and then using python on a different shell, we can test this to show it in action:

import requests
requests.get('http://127.0.0.1:8000/', headers={'jwt': MyJWT.new_token({'foo': 1}, 'mykey')})  # b'Hello World'

If we want to change the response when the JWT token is bad, you can override the method in bad_response in JWTPydanticMiddleware, such as below:

class MyMiddleware(JWTPydanticMiddleware):
    def bad_response(self, token_error: str) -> JSONResponse:
        """Changing standard response to be a JSONResponse"""
        return JSONResponse(
            {"bad_token": token_error}, status_code=403
        )

python-jose keyword arguments

JWTPydantic uses python-jose to manage the JWT tokens. The extra features that are provided using this package can be easily used through the keyword argument jose_opts. For instance, we can add the 'at_hash' claim to our JWT token by specifying the keyword argument access_token.

MyJWT.new_token(
    claims,
    SECRET_KEY,
    jose_opts={"access_token": "1234"},
)

Metadata

Release files for jwt-pydantic 0.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for jwt-pydantic 0.0.7
File Size Uploaded Provenance Actions
jwt_pydantic-0.0.7.tar.gz 5.7 kB Without provenance Details for jwt_pydantic-0.0.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for jwt-pydantic 0.0.7
File Interpreter ABI Platform Actions
jwt_pydantic-0.0.7-py3-none-any.whl Python 3 none any Details for jwt_pydantic-0.0.7-py3-none-any.whl

Total release size: 12.2 kB

Release files / jwt_pydantic-0.0.7.tar.gz

Download URL jwt_pydantic-0.0.7.tar.gz
Size 5.7 kB
Tags Source
SHA-256 checksum
How to use checksums
0a04e579952e9a0c7b10cd2accb15d2aea70f3dbd8b24fbe9299955fe1d82be4
BLAKE2b-256 checksum
How to use checksums
69045e0e2d452bb43e7151785bed83dac9d4c43537266dee6236624fad154ffb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.4

Release files / jwt_pydantic-0.0.7-py3-none-any.whl

Download URL jwt_pydantic-0.0.7-py3-none-any.whl
Size 6.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
120d6ce3253345c868b23d928cdff281d112af90570412c3d0c4cf6b4ed79cdd
BLAKE2b-256 checksum
How to use checksums
392f6040e17e13ac8f085c77fb9adc73349dcbb01c50e5f12eb59ae76f811052
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.4

Security for jwt-pydantic 0.0.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page