Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Authentication.SignOutAsync does not delete auth cookie

According to ASP.NET Core documentation the method HttpContext.Authentication.SignOutAsync() must delete the authentication cookie as well.

Signing out

To sign out the current user, and delete their cookie (italics mine - A.C.) call the following inside your controller

await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");

But it does not! Everything else seems okay, esp. auth scheme, because user gets signed-in correctly and the cookie .AspNetCore. is created.

Any ideas why cookie remains after the user's sing-out?

like image 994
Alexander Christov Avatar asked Dec 13 '16 13:12

Alexander Christov


2 Answers

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); } 
like image 156
McGuireV10 Avatar answered Sep 30 '22 04:09

McGuireV10


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"); 
like image 21
Olakitan Avatar answered Sep 30 '22 04:09

Olakitan