我无法退出,即使在执行
User.Identity.IsAuthenticated
操作后,我的 logout
仍然显示“true”。
我的
Program.cs
文件是这样的
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate()
.AddCookie("Cookies", options =>
{
options.Cookie.Name = "Test";
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
});
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
而
Logout
的动作是这样的:
[AllowAnonymous]
public async Task<IActionResult> Logout()
{
if (HttpContext.Request.Cookies.Count > 0)
{
var siteCookies = HttpContext.Request.Cookies
.Where(c => c.Key.Contains(".AspNetCore.")
|| c.Key.Contains("Microsoft.Authentication"));
foreach (var cookie in siteCookies)
{
Response.Cookies.Delete(cookie.Key);
}
}
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
HttpContext.Session.Clear();
HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>()));
return RedirectToAction("Login", "Home");
}
有时,由于浏览器缓存问题或未能删除 cookie,会出现问题。您应该确保在
HttpContext.SignOutAsync
调用后清除浏览器 cookie。
代码中你的cookie清除过程如下:
if (HttpContext.Request.Cookies.Count > 0)
{
var siteCookies = HttpContext.Request.Cookies.Where(c => c.Key.Contains(".AspNetCore.") || c.Key.Contains("Microsoft.Authentication"));
foreach (var cookie in siteCookies)
{
Response.Cookies.Delete(cookie.Key);
}
}
此代码似乎删除包含
.AspNetCore.
或 Microsoft.Authentication
的 cookie。但是,您应该确保正确删除 cookie。相反,您可以尝试使用以下代码删除所有 cookie:
foreach (var cookie in Request.Cookies.Keys)
{
Response.Cookies.Delete(cookie);
}
此外,预计在
HttpContext.User
调用后,HttpContext.User
将自动更新为空身份,而不是为 HttpContext.SignOutAsync
分配空身份。因此,您可以删除该行HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>()));
。
通过进行这些更改,您可以验证注销过程并检查会话注销是否按预期运行。