Debian Codegraph @

docs/usage/security/guards.rst

raw
1 Guards
2 ======
3
4 Guards are :term:`callables <python:callable>` that receive two arguments - ``connection``, which is the :class:`Request <.connection.Request>` or :class:`WebSocket <.connection.WebSocket>` instance (both sub-classes of :class:`~.connection.ASGIConnection`), and ``route_handler``, which is a copy of the
5 :class:`~.handlers.BaseRouteHandler`. Their role is to *authorize* the request by verifying that
6 the connection is allowed to reach the endpoint handler in question. If verification fails, the guard should raise an
7 :exc:`HTTPException`, usually a :class:`~.exceptions.PermissionDeniedException` with a
8 ``status_code`` of ``403``.
9
10 To illustrate this we will implement a rudimentary role based authorization system in our Litestar app. As we have done
11 for ``authentication``, we will assume that we added some sort of persistence layer without actually specifying it in
12 the example.
13
14 We begin by creating an :class:`~enum.Enum` with two roles - ``consumer`` and ``admin``:
15
16 .. literalinclude:: /examples/security/guards.py
17 :language: python
18 :lines: 12-14
19 :caption: Defining the enum ``UserRole``
20
21 Our ``User`` model will now look like this:
22
23 .. literalinclude:: /examples/security/guards.py
24 :language: python
25 :lines: 17-24
26 :caption: User model for role based authorization
27
28 Given that the ``User`` model has a ``role`` property we can use it to authorize a request.
29 Let us create a guard that only allows admin users to access certain route handlers and then add it to a route
30 handler function:
31
32 .. literalinclude:: /examples/security/guards.py
33 :language: python
34 :lines: 27-29, 32-33
35 :caption: Defining the guard ``admin_user_guard`` used to authorize certain route handlers
36
37 Here, the ``admin_user_guard`` guard checks if the user is an admin.
38
39 The connection has a `user` object attached to it thanks to the JWT middleware, see :doc:`authentication </usage/security/jwt>`
40 and in particular the :meth:`JWTAuth.retrieve_user_handler` method.
41
42 Thus, only an admin user would be able to send a post request to the ``create_user`` handler.
43
44 Guard scopes
45 ------------
46
47 Guards are part of Litestar's :ref:`layered architecture <usage/applications:layered architecture>` and can be declared
48 on all layers of the app - the Litestar instance, routers, controllers, and individual route handlers:
49
50 .. literalinclude:: /examples/security/guards.py
51 :language: python
52 :lines: 36-49
53 :caption: Declaring guards on different layers of the app
54
55 The placement of guards within the Litestar application depends on the scope and level of access control needed:
56
57 - Should restrictions apply to individual route handlers?
58 - Is the access control intended for all actions within a controller?
59 - Are you aiming to secure all routes managed by a specific router?
60 - Or do you need to enforce access control across the entire application?
61
62 As you can see in the above examples - ``guards`` is a :class:`list`. This means you can add **multiple** guards at
63 every layer. Unlike :doc:`dependencies </usage/dependency-injection>` , guards do not override each other but are
64 rather *cumulative*. This means that you can define guards on different layers of your app, and they will combine.
65
66 .. caution::
67
68 If guards are placed at the controller or the app level, they **will** be executed on all ``OPTIONS`` requests as well.
69 For more details, including a workaround, refer https://github.com/litestar-org/litestar/issues/2314.
70
71
72 The route handler "opt" key
73 ---------------------------
74
75 Occasionally there might be a need to set some values on the route handler itself - these can be permissions, or some
76 other flag. This can be achieved with :ref:`the opts kwarg <handler_opts>` of route handler
77
78 To illustrate this let us say we want to have an endpoint that is guarded by a "secret" token, to which end we create
79 the following guard:
80
81 .. literalinclude:: /examples/security/guards.py
82 :language: python
83 :lines: 52-61