Movatterモバイル変換


[0]ホーム

URL:


跳转至
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

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

🌐 由 AI 与人类协作翻译

本翻译由人类引导的 AI 生成。🤝

可能存在误解原意或不够自然等问题。🤖

你可以通过帮助我们更好地引导 AI LLM来改进此翻译。

英文版本

在 FastAPI0.122.0 版本之前,当内置的安全工具在认证失败后向客户端返回错误时,会使用 HTTP 状态码403 Forbidden

从 FastAPI0.122.0 版本开始,它们改用更合适的 HTTP 状态码401 Unauthorized,并在响应中返回合理的WWW-Authenticate 头,遵循 HTTP 规范,RFC 7235RFC 9110

但如果由于某些原因你的客户端依赖旧行为,你可以在你的安全类中重写方法make_not_authenticated_error 来回退到旧行为。

例如,你可以创建一个HTTPBearer 的子类,使其返回403 Forbidden 错误,而不是默认的401 Unauthorized 错误:

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}

提示

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


[8]ページ先頭

©2009-2026 Movatter.jp