Skip to content

Commit 592181d

Browse files
committed
Make FastAPI use the old 403 authentication error status codes
This is a (hopefully) temporarily hack to be compatible with FastAPI>=`0.122.0` because they now use 401 Unauthorized (instead of 403 Forbidden) on failed authentication. See: - https://github.com/fastapi/fastapi/releases/tag/0.122.0 - https://fastapi.tiangolo.com/how-to/authentication-error-status-code/
1 parent 33f4405 commit 592181d

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

server/parsec/asgi/administration.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
cast,
1414
)
1515

16-
from fastapi import APIRouter, Depends, HTTPException, Request, Response
16+
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
1717
from fastapi.responses import JSONResponse
1818
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
1919
from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt
@@ -68,7 +68,23 @@
6868

6969

7070
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()
7288

7389

7490
def check_administration_auth(

0 commit comments

Comments
 (0)