|
13 | 13 | cast, |
14 | 14 | ) |
15 | 15 |
|
16 | | -from fastapi import APIRouter, Depends, HTTPException, Request, Response |
| 16 | +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status |
17 | 17 | from fastapi.responses import JSONResponse |
18 | 18 | from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer |
19 | 19 | from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt |
|
68 | 68 |
|
69 | 69 |
|
70 | 70 | administration_router = APIRouter(tags=["administration"]) |
71 | | -security = HTTPBearer() |
| 71 | + |
| 72 | + |
| 73 | +# TODO: Use 401 Unauthorized instead of 403 Forbidden on failed authentication |
| 74 | +# Before FastAPI version 0.122.0, when the integrated security utilities returned an error to the client |
| 75 | +# after a failed authentication, they used the HTTP status code 403 Forbidden. |
| 76 | +# |
| 77 | +# Starting with FastAPI version 0.122.0, they use the more appropriate HTTP status code 401 Unauthorized, |
| 78 | +# and return a sensible WWW-Authenticate header in the response, following the HTTP specifications, RFC 7235, RFC 9110. |
| 79 | +# |
| 80 | +# This is a "hack" suggested in FastAPI docs to keep the old behavior. |
| 81 | +# See: https://fastapi.tiangolo.com/how-to/authentication-error-status-code/ |
| 82 | +class HTTPBearer403(HTTPBearer): |
| 83 | + def make_not_authenticated_error(self) -> HTTPException: |
| 84 | + return HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated") |
| 85 | + |
| 86 | + |
| 87 | +security = HTTPBearer403() |
72 | 88 |
|
73 | 89 |
|
74 | 90 | def check_administration_auth( |
|
0 commit comments