跳到内容

使用旧的 403 认证错误状态码

在 FastAPI 0.122.0 版本之前,当集成的安全工具在认证失败后向客户端返回错误时,它们使用的是 HTTP 状态码 403 Forbidden

从 FastAPI 0.122.0 版本开始,它们遵循 HTTP 规范 RFC 7235RFC 9110,使用更合适的 HTTP 状态码 401 Unauthorized,并在响应中返回一个合理的 WWW-Authenticate 标头。

但如果由于某些原因,您的客户端依赖于旧的行为,您可以通过在您的安全类中覆盖 make_not_authenticated_error 方法来恢复它。

例如,您可以创建一个 HTTPBearer 的子类,它会返回一个 403 Forbidden 错误,而不是默认的 401 Unauthorized 错误。

from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

app = FastAPI()


class HTTPBearer403(HTTPBearer):
    def make_not_authenticated_error(self) -> HTTPException:
        return HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated"
        )


CredentialsDep = Annotated[HTTPAuthorizationCredentials, Depends(HTTPBearer403())]


@app.get("/me")
def read_me(credentials: CredentialsDep):
    return {"message": "You are authenticated", "token": credentials.credentials}
🤓 其他版本和变体
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from typing_extensions import Annotated

app = FastAPI()


class HTTPBearer403(HTTPBearer):
    def make_not_authenticated_error(self) -> HTTPException:
        return HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated"
        )


CredentialsDep = Annotated[HTTPAuthorizationCredentials, Depends(HTTPBearer403())]


@app.get("/me")
def read_me(credentials: CredentialsDep):
    return {"message": "You are authenticated", "token": credentials.credentials}

提示

请注意,该函数返回的是异常实例,而不是抛出它。抛出异常的操作由其余的内部代码完成。