Debian Codegraph @

docs/examples/security/using_abstract_authentication_middleware.py

raw
1 from dataclasses import dataclass
2 from typing import Any
3
4 import anyio
5
6 from litestar import Litestar, MediaType, Request, Response, WebSocket, get, websocket
7 from litestar.connection import ASGIConnection
8 from litestar.datastructures import State
9 from litestar.di import Provide
10 from litestar.exceptions import NotAuthorizedException, NotFoundException
11 from litestar.middleware import AbstractAuthenticationMiddleware, AuthenticationResult
12 from litestar.middleware.base import DefineMiddleware
13
14 API_KEY_HEADER = "X-API-KEY"
15
16 TOKEN_USER_DATABASE = {"1": "user_authorized"}
17
18
19 @dataclass
20 class MyUser:
21 name: str
22
23
24 @dataclass
25 class MyToken:
26 api_key: str
27
28
29 class CustomAuthenticationMiddleware(AbstractAuthenticationMiddleware):
30 async def authenticate_request(self, connection: ASGIConnection) -> AuthenticationResult:
31 """Given a request, parse the request api key stored in the header and retrieve the user correlating to the token from the DB"""
32
33 # retrieve the auth header
34 auth_header = connection.headers.get(API_KEY_HEADER)
35 if not auth_header:
36 raise NotAuthorizedException()
37
38 # this would be a database call
39 token = MyToken(api_key=auth_header)
40 user = MyUser(name=TOKEN_USER_DATABASE.get(token.api_key))
41 if not user.name:
42 raise NotAuthorizedException()
43 return AuthenticationResult(user=user, auth=token)
44
45
46 @get("/")
47 def my_http_handler(request: Request[MyUser, MyToken, State]) -> None:
48 user = request.user # correctly typed as MyUser
49 auth = request.auth # correctly typed as MyToken
50 assert isinstance(user, MyUser)
51 assert isinstance(auth, MyToken)
52
53
54 @websocket("/")
55 async def my_ws_handler(socket: WebSocket[MyUser, MyToken, State]) -> None:
56 user = socket.user # correctly typed as MyUser
57 auth = socket.auth # correctly typed as MyToken
58 assert isinstance(user, MyUser)
59 assert isinstance(auth, MyToken)
60
61
62 @get(path="/", exclude_from_auth=True)
63 async def site_index() -> Response:
64 """Site index"""
65 exists = await anyio.Path("index.html").exists()
66 if exists:
67 async with await anyio.open_file(anyio.Path("index.html")) as file:
68 content = await file.read()
69 return Response(content=content, status_code=200, media_type=MediaType.HTML)
70 raise NotFoundException("Site index was not found")
71
72
73 async def my_dependency(request: Request[MyUser, MyToken, State]) -> Any:
74 user = request.user # correctly typed as MyUser
75 auth = request.auth # correctly typed as MyToken
76 assert isinstance(user, MyUser)
77 assert isinstance(auth, MyToken)
78
79
80 # you can optionally exclude certain paths from authentication.
81 # the following excludes all routes mounted at or under `/schema*`
82 auth_mw = DefineMiddleware(CustomAuthenticationMiddleware, exclude="schema")
83
84 app = Litestar(
85 route_handlers=[site_index, my_http_handler, my_ws_handler],
86 middleware=[auth_mw],
87 dependencies={"some_dependency": Provide(my_dependency)},
88 )