Commit ·
d4c432e
1
Parent(s): c573ee8
feat(auth): add public endpoint handling in auth middleware
Browse filesThe authentication middleware now skips authentication for specified public endpoints, allowing requests to these endpoints to bypass token checks. This change improves the flexibility of the middleware by enabling unauthenticated access where necessary. The process time for requests to public endpoints is still measured and included in the response headers.
This update ensures that the application can handle both public and protected routes more efficiently.
main.py
CHANGED
|
@@ -15,8 +15,19 @@ security = HTTPBearer()
|
|
| 15 |
# Context variable to store the token
|
| 16 |
token_context = ContextVar('token', default=None)
|
| 17 |
|
|
|
|
|
|
|
|
|
|
| 18 |
@app.middleware("http")
|
| 19 |
async def auth_middleware(request: Request, call_next):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
try:
|
| 21 |
auth_header = request.headers.get('Authorization')
|
| 22 |
if not auth_header:
|
|
|
|
| 15 |
# Context variable to store the token
|
| 16 |
token_context = ContextVar('token', default=None)
|
| 17 |
|
| 18 |
+
# Liste des endpoints qui ne nécessitent pas d'authentification
|
| 19 |
+
PUBLIC_ENDPOINTS = {"/"}
|
| 20 |
+
|
| 21 |
@app.middleware("http")
|
| 22 |
async def auth_middleware(request: Request, call_next):
|
| 23 |
+
# Skip authentication for public endpoints
|
| 24 |
+
if request.url.path in PUBLIC_ENDPOINTS:
|
| 25 |
+
start_time = time.perf_counter()
|
| 26 |
+
response = await call_next(request)
|
| 27 |
+
process_time = time.perf_counter() - start_time
|
| 28 |
+
response.headers["X-Process-Time"] = str(process_time)
|
| 29 |
+
return response
|
| 30 |
+
|
| 31 |
try:
|
| 32 |
auth_header = request.headers.get('Authorization')
|
| 33 |
if not auth_header:
|