Fix sign-out with ASP.NET Identity Core 2.1
For a new app I’m writing using ASP.Net MVC Core 2.1, EF Core 2.1 and ASP.Net Identity 2.1 I had to implement the sign-out / log-out functionality. You may ask why, because this is shipped with ASP.Net Core OOTB? Yes – it is. But in the default template with ASP.Net Identity Core EF 2.1 it does not work.
I think I can work but depends on the kind auf authentication you activate. I use token authentication via cookies. The logoff action shipped with ASP.Net Core 2.1 doesn’t work for this. It forward you to the log-off page telling you, that you have been logged out but actually you are still logged in.
I figured that the cookie with the authentication token is still present in the the browser session – even after you called the default logout action. The token-authentication works the way the server generate an encrypted authentication token (basically a string) that is passed forth and back using a cookie. The server validates this token with each request. Normally there is no server-side token-store or so. So there is no need to actively log-out on the server-side.
To fix it I implemented my own action which removes this cookie and then redirect to the start-page of my app. To do this more reliable I gave the authentication cookie my own custom name.
In ConfigureServices() in Startup.cs I placed the following code to configure authentication:
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
options.Cookie.Name = GlobalConstants.AuthCookieName;
});
Check the custom name (stored in a global constant) for options.Cookie.Name.
Then I wrote my little logout action like this:
[Authorize]
[HttpGet]
public IActionResult Logout()
{
Response.Cookies.Delete(GlobalConstants.AuthCookieName);
return RedirectToAction("Index");
}
Finally I placed a link to this new Logout action in my user-menu.
That’s it. Hope it helps.