密码更新失败的最佳 HTTP 状态代码错误是什么?

What is the best HTTP status code error for failed password update?

我正在构建一些 REST API 以用于本机 iOS/Android 应用程序。 其中一个端点允许用户通过提供 2 个字段来更新其密码:old_passwordpassword.

old_password 不正确的情况下,我应该使用哪个 HTTP 状态代码?

我的第一个想法是 401 错误,但我已经在身份验证令牌无效时使用它,它会自动触发应用程序中的注销。

400 似乎不合适,因为请求实际上在语义上是正确的,它是一个特定的身份验证错误。也许 422?

要记住的一件事是状态代码,如响应 headers,是 元数据;它们的存在是为了让对您的 API 细节一无所知的通用组件可以智能地参与——例如,通过使缓存无效,或抛出对话框来收集身份验证凭据。

400 doesn't seem to fit because the request is actually semantically correct

实际上,400通常就可以了;客户端应该像对待 400 一样对待 unrecognized 4xx class 状态代码。换句话说,您可以使用 400,除非您特别想通过通用组件引起不同的行为。

对于您的具体情况,409 Conflict 可能是最接近的匹配项

The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict.

RFC 5789 suggests 409422 之间的区别可能很有趣。解释这个区别

422: This might include attempts to modify a resource in a way that would cause the resource to become invalid 409: the request cannot be applied given the state of the resource.

你也可以制作a reasonable argument that the entire 4xx class of response codes is inappropriate. For example, if the request method is POST,那么服务器希望

process the representation enclosed in the request according to the resource's own specific semantics

它做了什么;成功,甚至。它只是没有产生最普遍预期的成功结果。

另一方面,JSON补丁会反其道而行之;您更改密码的尝试可能类似于

[
    { "op": "test", "path": "/password", "value": "old_password" },
    { "op": "replace", "path": "/password", "value": "new_password" }
]

如果您在 test 中提供了错误的密码,那么该操作将被视为 不成功 ,这反过来意味着 PATCH 不成功。这反过来会调用参数进行错误处理,如 HTTP Patch.

中所述