RESTful API 中未登录与未授权的不同 HTTP 状态
因此,在我的 API 中发送一些不同的状态标头,包括 404
、409
、201
、302
等。现在我遇到了 401 Unauthorized
问题。目前,如果用户未登录(整个 API 均受权限管理)或者用户不满足正在检索/修改的特定资源的特定访问要求,我就会发送该信息。
现在,我还控制前端客户端(一个 jQuery/HTML 应用程序),并且我想区分 401
的两种情况。对于未登录,我应该使用不同的状态吗?处理它的最佳方法是在标题旁边发送正文内容吗?
So send a few different status headers in my API including 404
, 409
, 201
, 302
and the like. Now I'm running into issues with 401 Unauthorized
. I'm currently sending it if a user is not logged in (the entire API is rights managed) or if a user doesn't satisfy the specific access requirements for the particular resource being retrieved/modified.
Now, I also control the frontend client (a jQuery/HTML application), and I'd like to differentiate between the two cases for 401
. Is there a distinct status I should be using for not logged in? Is the best way to handle it to send body content alongside the header?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用
403
来指示用户无权访问该资源。使用401
用于指示用户需要提供您当前使用的凭据。请参阅401
和403
的说明 此处。You should use
403
to indicate that the user isn't authorized to access the resource. Using401
is for indicating that the user needs to supply credentials just as you are currently using it. See the descriptions of401
and403
here.正如laz所说,当您对用户进行身份验证时,您应该使用
403
,但用户无权执行她所要求的操作。例如,您可能允许获取资源,但不允许删除或放置。无论如何,响应正文应始终包含更多信息,即使它是错误响应。这为客户提供了一条出路,希望继续前进(使用嵌入式链接)或通过提供有关如何继续的足够信息(例如“我的记录表明您没有删除 XXX 的权限,请联系您的系统管理员并询问FOOBAR 许可”)。
As laz say, you should use
403
when you've authenticated the user, but the user doesn't have permission to do what she's asking for. e.g. you might allow GET'ing a resource, but not DELETE or PUT.In any case, the response body should always contain more information, even when it's an error response. This allows a client a way out, hopefully moving forward (using embedded links) or by providing enough information on how to proceed (e.g. "My records indicate that you do not have permission to delete XXX, please contact your system administrator and ask for the FOOBAR permission").