According to ASP.NET Core documentation the method HttpContext.Authentication.SignOutAsync()
must delete the authentication cookie as well.
Here's the code that deletes the cookie (If nothing else helps, use brute force):
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);
}
Bad, bad, bad! Seems like a very ugly patch! But works... :(
Any other solutions?
You didn't post enough code to tell, but I suspect after you call SignOutAsync
you have some type of redirect (for example, RedirectToAction
) which overwrites the redirect to the OIDC endsession URL that SignOutAsync
tries to issue.
(The same explanation for the redirect overwrite problem is given here by Microsoft's HaoK.)
Edit: If my speculation above is correct, the solution is to send a redirect URL in an AuthenticationProperties
object with the final 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);
}
In my case McGuireV10's answer didn't work as await context.SignOutAsync("oidc", prop);
did not redirect to my given redirectUri.
I solved it by adding HttpContext.Response.Redirect(redirectUri);
after the SignOutAsync call.
I've got the same problem. SignOutAsync does not work as should .
I found this:
Response.Cookies.Delete(".AspNetCore.<nameofcookie>");
I had the same issue recently. In my case, the browser had created multiple cookies. One with a name like ".AspNetCore.Antiforgery" and another one with a custom name that I had set for my cookie in startup.cs.
What solved the error for me was the first part of JTvermose's answer with some changes. I added the code below to my logout method. Worked like a charm.
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();
return RedirectToPage("/Index");
Solved the issue with this first line.
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// await _SignInManager.SignOutAsync();
// HttpContext.Response.Cookies.Delete(".AspNetCore.Cookies");