पुराने 403 Authentication Error Status Codes का उपयोग करें¶
🌐 एआई और मनुष्यों द्वारा किया गया अनुवाद
यह अनुवाद मनुष्यों के मार्गदर्शन में एआई द्वारा किया गया है। 🤝
इसमें मूल अर्थ को गलत समझने या अप्राकृतिक लगने आदि जैसी गलतियाँ हो सकती हैं। 🤖
आप हमें एआई LLM को बेहतर मार्गदर्शन करने में मदद करके इस अनुवाद को बेहतर बना सकते हैं।
FastAPI version 0.122.0 से पहले, जब integrated security utilities failed authentication के बाद client को error लौटाती थीं, तो वे HTTP status code 403 Forbidden का उपयोग करती थीं।
FastAPI version 0.122.0 से शुरू होकर, वे अधिक उपयुक्त HTTP status code 401 Unauthorized का उपयोग करती हैं, और HTTP specifications, RFC 7235, RFC 9110 का पालन करते हुए response में एक उचित WWW-Authenticate header लौटाती हैं।
लेकिन अगर किसी कारण से आपके clients पुराने behavior पर निर्भर हैं, तो आप अपनी security classes में method make_not_authenticated_error को override करके उस पर वापस जा सकते हैं।
उदाहरण के लिए, आप HTTPBearer का एक subclass बना सकते हैं जो default 401 Unauthorized error के बजाय 403 Forbidden error लौटाता है:
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}
टिप
ध्यान दें कि function exception instance लौटाता है, उसे raise नहीं करता। raising बाकी internal code में किया जाता है।