| 1 |
from os import environ |
| 2 |
from typing import Any, Dict, Optional |
| 3 |
from uuid import UUID, uuid4 |
| 4 |
|
| 5 |
from pydantic import BaseModel, EmailStr |
| 6 |
|
| 7 |
from litestar import Litestar, Request, Response, get, post |
| 8 |
from litestar.connection import ASGIConnection |
| 9 |
from litestar.openapi.config import OpenAPIConfig |
| 10 |
from litestar.security.jwt import JWTAuth, Token |
| 11 |
|
| 12 |
|
| 13 |
# Let's assume we have a User model that is a pydantic model. |
| 14 |
# This though is not required - we need some sort of user class - |
| 15 |
# but it can be any arbitrary value, e.g. an SQLAlchemy model, a representation of a MongoDB etc. |
| 16 |
class User(BaseModel): |
| 17 |
id: UUID |
| 18 |
name: str |
| 19 |
email: EmailStr |
| 20 |
|
| 21 |
|
| 22 |
MOCK_DB: Dict[str, User] = {} |
| 23 |
BLOCKLIST: Dict[str, str] = {} |
| 24 |
|
| 25 |
|
| 26 |
# JWTAuth requires a retrieve handler callable that receives the JWT token model and the ASGI connection |
| 27 |
# and returns the 'User' instance correlating to it. |
| 28 |
# |
| 29 |
# Notes: |
| 30 |
# - 'User' can be any arbitrary value you decide upon. |
| 31 |
# - The callable can be either sync or async - both will work. |
| 32 |
async def retrieve_user_handler(token: Token, connection: "ASGIConnection[Any, Any, Any, Any]") -> Optional[User]: |
| 33 |
# logic here to retrieve the user instance |
| 34 |
return MOCK_DB.get(token.sub) |
| 35 |
|
| 36 |
|
| 37 |
# If you want to use JWTAuth with revoking tokens, you have to define a handler of revoked tokens |
| 38 |
# with your custom logic. |
| 39 |
async def revoked_token_handler(token: Token, connection: "ASGIConnection[Any, Any, Any, Any]") -> bool: |
| 40 |
jti = token.jti # Unique token identifier (JWT ID) |
| 41 |
if jti: |
| 42 |
# Check if the token is already revoked in the BLOCKLIST |
| 43 |
revoked = BLOCKLIST.get(jti) |
| 44 |
if revoked: |
| 45 |
return True |
| 46 |
return False |
| 47 |
|
| 48 |
|
| 49 |
jwt_auth = JWTAuth[User]( |
| 50 |
retrieve_user_handler=retrieve_user_handler, |
| 51 |
revoked_token_handler=revoked_token_handler, |
| 52 |
token_secret=environ.get("JWT_SECRET", "abcd123"), |
| 53 |
# we are specifying which endpoints should be excluded from authentication. In this case the login endpoint |
| 54 |
# and our openAPI docs. |
| 55 |
exclude=["/login", "/schema"], |
| 56 |
) |
| 57 |
|
| 58 |
|
| 59 |
# Given an instance of 'JWTAuth' we can create a login handler function: |
| 60 |
@post("/login") |
| 61 |
async def login_handler(data: User) -> Response[User]: |
| 62 |
MOCK_DB[str(data.id)] = data |
| 63 |
# you can do whatever you want to update the response instance here |
| 64 |
# e.g. response.set_cookie(...) |
| 65 |
return jwt_auth.login( |
| 66 |
identifier=str(data.id), |
| 67 |
token_unique_jwt_id=uuid4().hex, |
| 68 |
token_extras={"email": data.email}, |
| 69 |
response_body=data, |
| 70 |
) |
| 71 |
|
| 72 |
|
| 73 |
# Also we can create a logout |
| 74 |
@post("/logout") |
| 75 |
async def logout_handler(request: Request["User", Token, Any]) -> Dict[str, str]: |
| 76 |
# Your custom logic here |
| 77 |
# For example |
| 78 |
jti = request.auth.jti |
| 79 |
if jti: |
| 80 |
BLOCKLIST[jti] = "revoked" |
| 81 |
return {"message": "Token has been revoked."} |
| 82 |
return {"message": "No valid token found."} |
| 83 |
|
| 84 |
|
| 85 |
# We also have some other routes, for example: |
| 86 |
@get("/some-path", sync_to_thread=False, middleware=[jwt_auth.middleware]) |
| 87 |
def some_route_handler(request: "Request[User, Token, Any]") -> Any: |
| 88 |
# request.user is set to the instance of user returned by the middleware |
| 89 |
assert isinstance(request.user, User) |
| 90 |
# request.auth is the instance of 'litestar.security.jwt.Token' created from the data encoded in the auth header |
| 91 |
assert isinstance(request.auth, Token) |
| 92 |
# do stuff ... |
| 93 |
|
| 94 |
|
| 95 |
# We create our OpenAPIConfig as usual - the JWT security scheme will be injected into it. |
| 96 |
openapi_config = OpenAPIConfig( |
| 97 |
title="My API", |
| 98 |
version="1.0.0", |
| 99 |
) |
| 100 |
|
| 101 |
# We initialize the app instance and pass the jwt_auth 'on_app_init' handler to the constructor. |
| 102 |
# The hook handler will inject the JWT middleware and openapi configuration into the app. |
| 103 |
app = Litestar( |
| 104 |
route_handlers=[login_handler, logout_handler, some_route_handler], |
| 105 |
on_app_init=[jwt_auth.on_app_init], |
| 106 |
openapi_config=openapi_config, |
| 107 |
) |