Fra*_*ser 5 c# authentication asp.net-core
我在使 ASP.NET Core 3.0 中的身份验证 cookie 无效时遇到问题。
设想
我有一个登录网站的用户。当他们单击注销按钮时,它会调用以下代码:
[HttpGet]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
HttpContext.Session.Clear();
return RedirectToAction("Index", "Home");
}
Run Code Online (Sandbox Code Playgroud)
这成功地清除了浏览器中的所有 cookie,但是,如果我.AspNetCore.Cookies在注销之前获取会话 cookie 的值,然后在以后的请求中重新添加它,我就可以导航到需要用户身份验证的页面。
任何人都可以帮助解决这个问题?
注意:最初的问题是关于如何清除用户会话,但我后来意识到这实际上是关于 cookie 本身而不是服务器端会话的问题。
注销的问题在于它只是删除了 cookie,但它本身的 cookie 仍然有效。
唯一的解决方案是添加 Cookie SessionStore 并将其添加到 cookie 身份验证处理程序中。通过添加一,您可以确保注销后 cookie 无法重复使用,第二个好处是 cookie 大小也减小了。
您可以向 cookie 处理程序添加一个,如下所示:
.AddCookie("cookie", o =>
{
//...
o.SessionStore = new MySessionStore();
})
Run Code Online (Sandbox Code Playgroud)
要实现会话存储,您需要做的就是实现这个接口:
/// <summary>
/// This provides an abstract storage mechanic to preserve the identity
/// information on the server while only sending a simple identifier
/// key to the client. This is most commonly used to mitigate
/// issues with serializing large identities into cookies.
/// </summary>
public interface ITicketStore
{
/// <summary>
/// Store the identity ticket and return the associated key.
/// </summary>
Task<string> StoreAsync(AuthenticationTicket ticket);
/// <summary>
/// Tells the store that the given identity should be updated.
/// </summary>
Task RenewAsync(string key, AuthenticationTicket ticket);
/// <summary>
/// Retrieves an identity from the store for the given key.
/// </summary>
Task<AuthenticationTicket?> RetrieveAsync(string key);
/// <summary>
/// Remove the identity associated with the given key.
/// </summary>
Task RemoveAsync(string key);
}
Run Code Online (Sandbox Code Playgroud)
有关此内容以及如何实现会话存储的更多详细信息,请参阅我的博客文章:
通过减少 Cookie 来提高 ASP.NET Core 安全性
| 归档时间: |
|
| 查看次数: |
2637 次 |
| 最近记录: |