我在用户注销时删除 cookie 时遇到了一些麻烦。
我正在学习 MVC Asp.Net 并且我已经创建了默认的 MVC5 应用程序。我已经注册并使用帐户登录,一切正常。但是当我点击注销时它正在工作,它会将我重定向到主页但它不会删除 cookie。
我正在使用 this 检查 cookie chrome 的扩展“编辑此 Cookie”。
首先,我登录然后使用 EditThisCookie 扩展复制 cookie,然后注销并删除 cookie。现在,当我将复制的 cookie 粘贴到 EditTshiCookie 扩展程序并刷新页面时,它会使用相同的帐户登录。 Cookie 不会被删除。
注销方法
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Index", "Home");
}
我试过来自this question
Request.GetOwinContext().Authentication.SignOut();
Request.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.Current.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
最佳答案
您对基于 owin cookie 的身份验证的理解方式是错误的:)
- 登录到应用程序会创建 authcookie,其中包含有关用户身份验证和声明(权限)的信息。没有任何内容写入服务器 session 或以任何其他方式保留。
- 在登录 cookie 解码和验证用户是否仍通过身份验证后的每个请求中。如果为真,它会解码声明,以便以后可以由
AuthorizeAttribute
使用
- 注销会从浏览器中删除该 cookie,但如果您以任何方式保留该 cookie 并将其再次放入另一个请求中,owin 将认为它仍然是经过身份验证的有效用户。
Session.Abandon
无济于事,因为 DefaultAuthenticationTypes.ApplicationCookie
不是基于 session 的。
如果这不是我们想要的行为。您可以向 session 添加一些标志(IsAuthorized
)并 checkin 。 Global.asax Application_PreRequestHandlerExecute
然后重定向到登录表单。这样您将获得有关服务器和客户端的信息。但请记住,如果服务器 session 状态失败(例如 IIS 重启),所有实际登录的用户都将被注销。
关于基于 cookie 的身份验证的更多信息 link
关于c# - OWIN - 注销 MVC 时删除 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35550025/