RESTful API 中未登录与未授权的不同 HTTP 状态

发布于 2024-09-15 08:37:22 字数 318 浏览 4 评论 0原文

因此,在我的 API 中发送一些不同的状态标头,包括 404409201302 等。现在我遇到了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我一向站在原地 2024-09-22 08:37:22

您应该使用 403 来指示用户无权访问该资源。使用 401 用于指示用户需要提供您当前使用的凭据。请参阅 401403 的说明 此处

You should use 403 to indicate that the user isn't authorized to access the resource. Using 401 is for indicating that the user needs to supply credentials just as you are currently using it. See the descriptions of 401 and 403 here.

离旧人 2024-09-22 08:37:22

正如laz所说,当您对用户进行身份验证时,您应该使用403,但用户无权执行她所要求的操作。例如,您可能允许获取资源,但不允许删除或放置。

  • 401 是不正确的,因为它基本上表示“我不认识这些凭据”
  • 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.

  • 401 would be incorrect since it basically says that "I don't recognise these credentials"
  • 403 is correct since it says that "You're not allowed to do this"

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").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文