You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/guards.md
+19-7Lines changed: 19 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
# Guards and Authentication
2
2
3
-
PyNest now supports route guards similar to NestJS. Guards are classes that implement custom authorization logic. Use the `UseGuards` decorator to attach one or more guards to a controller or to specific routes.
3
+
PyNest now supports route guards similar to NestJS. Guards are classes that implement custom authorization logic. Use the `UseGuards` decorator to attach one or more guards to a controller or to specific routes. If a guard defines a FastAPI security scheme via the ``security_scheme`` attribute, the generated OpenAPI schema will mark the route as protected and the interactive docs will allow entering credentials.
4
4
5
5
```python
6
6
from fastapi import Request
@@ -23,26 +23,31 @@ When the guard returns `False`, a `403 Forbidden` response is sent automatically
23
23
24
24
## JWT Authentication Example
25
25
26
-
You can use third-party libraries like `pyjwt`to validate tokens inside a guard.
26
+
You can use third-party libraries like `pyjwt`together with FastAPI's security utilities.
27
27
28
28
```python
29
29
import jwt
30
30
from fastapi import Request
31
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
Attach the guard with `@UseGuards(JWTGuard)` on controllers or routes to secure them.
50
+
Attach the guard with `@UseGuards(JWTGuard)` on controllers or routes to secure them. Because ``JWTGuard`` specifies a ``security_scheme`` the route will display a lock icon in the docs and allow entering a token.
46
51
47
52
## Controller vs. Route Guards
48
53
@@ -102,3 +107,10 @@ class AsyncGuard(BaseGuard):
102
107
103
108
PyNest awaits the result automatically.
104
109
110
+
## OpenAPI Integration
111
+
112
+
When a guard sets the ``security_scheme`` attribute, the generated OpenAPI schema
113
+
includes the corresponding security requirement. The docs page will show a lock
114
+
icon next to the route and present an input box for the token or credentials.
115
+
This works with any ``fastapi.security`` scheme (e.g. ``HTTPBearer``, ``OAuth2PasswordBearer``).
0 commit comments