Owin 未经授权的请求未注销用户

Owin unauthorized request not signing out user

在我的 ASP MVC 项目中,我实现了 OWIN CookieAuthentication。除了未经授权的请求外,一切都很好。 例如,考虑流程:

  1. 用户登录
  2. 用户点击了用户无权访问的端点。

限制通过:

[Authorize(Roles = "SomeRoleUserDontHaAssigned")]
public ActionResult SomeAction()...

发生这种情况时,用户会被重定向到 Account/Login 路线(没问题),但他不会注销(这是我所期望的)。

这是预期的行为吗,所以我应该实施我自己的 AuthorizeAttribute,我应该在其中手动删除 cookie(或调用 Account/SignOut)?还是我遗漏了什么?

我决定把它放在一个答案中,因为它可能不适合单个评论。

首先,让我们回到基础——HTTP 状态码。在谈论身份验证和授权时,您主要关注两个代码 - 401 和 403。

来自 RFC 7235 规范:

3.1。 401 未经授权 (https://www.rfc-editor.org/rfc/rfc7235#section-3.1)

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.

6.5.3。 403 禁止 (https://www.rfc-editor.org/rfc/rfc7231#section-6.5.3)

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

换句话说,401表示认证有问题(用户未认证或认证错误)。可以提供有效凭证并重试。同时403表示权限有问题。服务器知道用户是谁但拒绝访问 - 不应使用相同的凭据再次尝试。

OWIN CookieAuthentication 只是坐在那里侦听 401 错误代码 returned。如果它检测到此类代码,则响应将替换为重定向到维护 return 地址的登录页面。

尽管名称为 AuthorizeAttribute,但它实际上会生成 401 状态代码。 https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Http/AuthorizeAttribute.cs#L155

因此,用户被带到登录页面。

如果你想改变它,你可能需要实现你自己的 AuthorizeAttribute。然后你可以检查用户是否已经登录和 return 403 状态。如果用户还没有登录,就return 401.