validation - 如果用户尝试使用错误的用户名/密码登录,但格式正确,返回的适当 HTTP 状态代码是什么?

标签 validation rest django-rest-framework restful-authentication http-status-codes

这里发布了一个类似的问题:What's an appropriate HTTP status code to return by a REST API service for a validation failure?

上面线程中的答案指出“例如,如果 URI 应该具有 ISO-8601 日期,而您发现它的格式错误或指的是 2 月 31 日,那么您将返回 HTTP 400。如果您期望,同上实体主体中格式良好的 XML 并且无法解析。”

但是,如果用户提交正确格式的数据会发生什么?我的意思是,用户提交了一个简单的字母字符串/文本作为用户名和密码(这对我的应用程序完全有效)。唯一的问题是密码与用户名不匹配。在这种情况下,400 将是不正确的,因为它是完全有效的语法并且格式正确。

401 是不正确的(如此处所建议的: Which HTTP status code to say username or password were incorrect? ),因为用户并未尝试访问任何页面,他只是尝试登录并输入不匹配的数据。

如果你回顾我链接到的第一篇文章,第二个答案指出 422 是正确的响应(对我来说它看起来是正确的),但是,我使用的是 Django Rest Framework 并且 422 不是状态代码的一部分(a可以在此处找到属于 DRF 的状态代码列表:http://www.django-rest-framework.org/api-guide/status-codes/#client-error-4xx)

404 看起来也不对,因为数据被成功接受而不是被拒绝。

话虽如此,应该使用的真正正确的响应是什么?

最佳答案

如果您严格使用 RFC 7235 为您的 REST API 提供的 HTTP 身份验证框架,正确的 HTTP 代码实际上是 401。来自 the RFC :

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource.

If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The user agent MAY repeat the request with a new or replaced Authorization header field (Section 4.2).


您的 REST API 应该使用 authentication scheme某种形式,以便向您的客户端返回有效的 401 响应。
RFC 7235 第 4 页的另一个相关部分:

Upon receipt of a request for a protected resource that omits
credentials, contains invalid credentials (e.g., a bad password) or
partial credentials (e.g., when the authentication scheme requires
more than one round trip), an origin server SHOULD send a 401
(Unauthorized) response that contains a WWW-Authenticate header field with at least one (possibly new) challenge applicable to the
requested resource.


更高级别的响应,例如为视觉用户呈现的登录页面(通过 302 从 protected 资源重定向),最好使用 200 状态代码(例如,根据 @KernelDeimos 的回答)。由于登录页面通常是他们自己的资源(例如 /login?redirect=original-resource ),未经身份验证的用户仍然有权查看此页面,即使他们提供了不正确的用户名/密码。然后,您将经过身份验证的用户重定向回资源,此时将显示 200(如果允许)或 403(如果用户被禁止查看资源)。
401 可以与可视化登录页面一起发挥作用的区域是一个前端库,它利用 XHR 请求利用 REST API,然后将来自 REST API 的 401 响应中继回登录页面上的有意义的格式。

关于validation - 如果用户尝试使用错误的用户名/密码登录,但格式正确,返回的适当 HTTP 状态代码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32752578/

相关文章:

python - Django REST 框架 : "This field is required." with required=False and unique_together

asp.net - 格式验证摘要

javascript - 如何在在线表单中验证验证码

c# - 如何使用 oAuth token

c# - Web API 2.0 异常处理

spring - 构建可扩展的 Spring MVC 应用程序

Mysql 连接过多 : Django sqlAlchemy

Django REST分页相对URL而不是ListAPIView中的绝对URL

c# - 动态注释/属性值

javascript - 基本正则表达式问题