Debian Codegraph @

docs/examples/security/jwt/using_jwt_cookie_auth.py

raw
1 import secrets
2 from os import environ
3 from typing import Any, Dict, Optional
4 from uuid import UUID
5
6 from pydantic import BaseModel, EmailStr
7
8 from litestar import Litestar, Request, Response, get, post
9 from litestar.connection import ASGIConnection
10 from litestar.openapi.config import OpenAPIConfig
11 from litestar.security.jwt import JWTCookieAuth, Token
12
13
14 # Let's assume we have a User model that is a pydantic model.
15 # This though is not required - we need some sort of user class -
16 # but it can be any arbitrary value, e.g. an SQLAlchemy model, a representation of a MongoDB etc.
17 class User(BaseModel):
18 id: UUID
19 name: str
20 email: EmailStr
21
22
23 MOCK_DB: Dict[str, User] = {}
24
25
26 # JWTCookieAuth 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 jwt_cookie_auth = JWTCookieAuth[User](
38 retrieve_user_handler=retrieve_user_handler,
39 token_secret=environ.get("JWT_SECRET", secrets.token_hex()),
40 # we are specifying which endpoints should be excluded from authentication. In this case the login endpoint
41 # and our openAPI docs.
42 exclude=["/login", "/schema"],
43 # Tip: We can optionally supply cookie options to the configuration. Here is an example of enabling the secure cookie option
44 # secure=True,
45 )
46
47
48 # Given an instance of 'JWTCookieAuth' we can create a login handler function:
49 @post("/login")
50 async def login_handler(data: "User") -> "Response[User]":
51 MOCK_DB[str(data.id)] = data
52 return jwt_cookie_auth.login(identifier=str(data.id), response_body=data)
53
54
55 # We also have some other routes, for example:
56 @get("/some-path", sync_to_thread=False)
57 def some_route_handler(request: "Request[User, Token, Any]") -> Any:
58 # request.user is set to the instance of user returned by the middleware
59 assert isinstance(request.user, User)
60 # request.auth is the instance of 'litestar_jwt.Token' created from the data encoded in the auth header
61 assert isinstance(request.auth, Token)
62 # do stuff ...
63
64
65 # We create our OpenAPIConfig as usual - the JWT security scheme will be injected into it.
66 openapi_config = OpenAPIConfig(
67 title="My API",
68 version="1.0.0",
69 )
70
71 # We initialize the app instance and pass the jwt_cookie_auth 'on_app_init' handler to the constructor.
72 # The hook handler will inject the JWT middleware and openapi configuration into the app.
73 app = Litestar(
74 route_handlers=[login_handler, some_route_handler],
75 on_app_init=[jwt_cookie_auth.on_app_init],
76 openapi_config=openapi_config,
77 )