根据ASP.NET Core documentation,方法HttpContext.Authentication.SignOutAsync()
也必须删除身份验证cookie。
退出
要退出当前用户,并删除他们的cookie(斜体我的 - A.C.),请在控制器内调用以下内容
await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
但事实并非如此!其他一切似乎都没问题,尤其是auth scheme,因为用户正确登录了cookie .AspNetCore。被建造。
任何想法为什么cookie在用户唱出后仍然存在?
您没有发布足够的代码来告诉我,但我怀疑在您调用SignOutAsync
后,您有某种类型的重定向(例如,RedirectToAction
),它会将重定向覆盖到SignOutAsync
尝试发布的OIDC endsession URL。
(对于重定向覆盖问题的相同解释由Microsoft的HaoK给出here。)
编辑:如果我的推测是正确的,解决方案是在AuthenticationProperties
对象中发送一个重定向URL与最终的SignOutAsync
:
// in some controller/handler, notice the "bare" Task return value
public async Task LogoutAction()
{
// SomeOtherPage is where we redirect to after signout
await MyCustomSignOut("/SomeOtherPage");
}
// probably in some utility service
public async Task MyCustomSignOut(string redirectUri)
{
// inject the HttpContextAccessor to get "context"
await context.SignOutAsync("Cookies");
var prop = new AuthenticationProperties()
{
RedirectUri = redirectUri
});
// after signout this will redirect to your provided target
await context.SignOutAsync("oidc", prop);
}
我有同样的问题。 SignOutAsync不能正常工作。
我找到了这个:
Response.Cookies.Delete(".AspNetCore.<nameofcookie>");
我通过控制器中的Logout()方法中的以下代码段删除了我的网站cookie,解决了这个问题。我发现我的网站会创建多个cookie。
// Delete the authentication cookie(s) we created when user signed in
if (HttpContext.Request.Cookies[".MyCookie"] != null)
{
var siteCookies = HttpContext.Request.Cookies.Where(c => c.Key.StartsWith(".MyCookie"));
foreach (var cookie in siteCookies)
{
Response.Cookies.Delete(cookie.Key);
}
}
在Startup.cs中:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "Cookies",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Home/Index/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieName = ".MyCookie"
});
请注意,我不使用await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
,因为我正在使用OpenIdConnect与Google。
这是删除cookie的代码(如果没有其他帮助,请使用暴力):
await this.HttpContext.Authentication.SignOutAsync(<AuthenticationScheme>);
// ...
var cookie = this.Request.Cookies[<CookieName>];
if (cookie != null)
{
var options = new CookieOptions { Expires = DateTime.Now.AddDays(-1) };
this.Response.Cookies.Append(cookieName, cookie, options);
}
坏,坏,坏!看起来像一个非常难看的补丁!但是工作...... :(
还有其他方法吗?
用第一行解决了这个问题。
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// await _SignInManager.SignOutAsync();
// HttpContext.Response.Cookies.Delete(".AspNetCore.Cookies");