一般来说我们认为 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