Debian Codegraph @

docs/examples/security/jwt/using_oauth2_password_bearer.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 OAuth2Login, OAuth2PasswordBearerAuth, 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 # OAuth2PasswordBearerAuth 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 oauth2_auth = OAuth2PasswordBearerAuth[User](
38 retrieve_user_handler=retrieve_user_handler,
39 token_secret=environ.get("JWT_SECRET", secrets.token_hex()),
40 # we are specifying the URL for retrieving a JWT access token
41 token_url="/login",
42 # we are specifying which endpoints should be excluded from authentication. In this case the login endpoint
43 # and our openAPI docs.
44 exclude=["/login", "/schema"],
45 )
46
47
48 # Given an instance of 'OAuth2PasswordBearerAuth' we can create a login handler function:
49 @post("/login")
50 async def login_handler(request: "Request[Any, Any, Any]", data: "User") -> "Response[OAuth2Login]":
51 MOCK_DB[str(data.id)] = data
52 # if we do not define a response body, the login process will return a standard OAuth2 login response. Note the `Response[OAuth2Login]` return type.
53
54 # you can do whatever you want to update the response instance here
55 # e.g. response.set_cookie(...)
56 return oauth2_auth.login(identifier=str(data.id))
57
58
59 @post("/login_custom")
60 async def login_custom_response_handler(data: "User") -> "Response[User]":
61 MOCK_DB[str(data.id)] = data
62
63 # you can do whatever you want to update the response instance here
64 # e.g. response.set_cookie(...)
65 return oauth2_auth.login(identifier=str(data.id), response_body=data)
66
67
68 # We also have some other routes, for example:
69 @get("/some-path", sync_to_thread=False)
70 def some_route_handler(request: "Request[User, Token, Any]") -> Any:
71 # request.user is set to the instance of user returned by the middleware
72 assert isinstance(request.user, User)
73 # request.auth is the instance of 'litestar_jwt.Token' created from the data encoded in the auth header
74 assert isinstance(request.auth, Token)
75 # do stuff ...
76
77
78 # We create our OpenAPIConfig as usual - the JWT security scheme will be injected into it.
79 openapi_config = OpenAPIConfig(
80 title="My API",
81 version="1.0.0",
82 )
83
84 # We initialize the app instance and pass the oauth2_auth 'on_app_init' handler to the constructor.
85 # The hook handler will inject the JWT middleware and openapi configuration into the app.
86 app = Litestar(
87 route_handlers=[login_handler, some_route_handler],
88 on_app_init=[oauth2_auth.on_app_init],
89 openapi_config=openapi_config,
90 )