Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Use Old 403 Authentication Error Status Codes

Before FastAPI version0.122.0, when the integrated security utilities returned an error to the client after a failed authentication, they used the HTTP status code403 Forbidden.

Starting with FastAPI version0.122.0, they use the more appropriate HTTP status code401 Unauthorized, and return a sensibleWWW-Authenticate header in the response, following the HTTP specifications,RFC 7235,RFC 9110.

But if for some reason your clients depend on the old behavior, you can revert to it by overriding the methodmake_not_authenticated_error in your security classes.

For example, you can create a subclass ofHTTPBearer that returns a403 Forbidden error instead of the default401 Unauthorized error:

fromtypingimportAnnotatedfromfastapiimportDepends,FastAPI,HTTPException,statusfromfastapi.securityimportHTTPAuthorizationCredentials,HTTPBearerapp=FastAPI()classHTTPBearer403(HTTPBearer):defmake_not_authenticated_error(self)->HTTPException:returnHTTPException(status_code=status.HTTP_403_FORBIDDEN,detail="Not authenticated")CredentialsDep=Annotated[HTTPAuthorizationCredentials,Depends(HTTPBearer403())]@app.get("/me")defread_me(credentials:CredentialsDep):return{"message":"You are authenticated","token":credentials.credentials}

Tip

Notice that the function returns the exception instance, it doesn't raise it. The raising is done in the rest of the internal code.


[8]ページ先頭

©2009-2026 Movatter.jp