一般來說我們認為 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