django restframework 的 AuthenticationFailed 返回 401 還是返回 403 的問題


一般來說我們認為  AuthenticationFailed 就應該返回 401,然后前端根據 401 的status code來讓用戶重新登錄。

 

但是如果你使用 django rest framework的話,會有一個坑:

https://www.django-rest-framework.org/api-guide/exceptions/#authenticationfailed

https://www.django-rest-framework.org/api-guide/authentication/#unauthorized-and-forbidden-responses

正如上面文檔里面所說的:

AuthenticationFailed(detail=None, code=None)

Raised when an incoming request includes incorrect authentication.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.

 

When an unauthenticated request is denied permission there are two different error codes that may be appropriate.

HTTP 401 responses must always include a WWW-Authenticate header, that instructs the client how to authenticate. HTTP 403 responses do not include the WWW-Authenticate header.

The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response.

Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a 403 Permission Denied response will always be used, regardless of the authentication scheme.

 

 注意紅色標記的文字,意思就是 django 的 AuthenticationFailed 狀態碼有可能會返回403


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM