Skip to content

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:

public IActionResult Logout()
    return RedirectToAction("Index");

Finally I placed a link to this new Logout action in my user-menu.

That’s it. Hope it helps.

3 thoughts on “Fix sign-out with ASP.Net Identity Core 2.1 Leave a comment

  1. I have coded a login form. I don’t want it to logout automatically. On localhost, it doesn’t logout automatically, but on host server, it logs out whenever it wants (even while its active it logs out as well)


  2. I am vague on the GlobalConstants class. Or the value for:
    options.Cookie.Name = GlobalConstants.AuthCookieName;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: