Search code examples
sessioncookiesasp.net-coreasp.net-core-identity

ASP.NET Core Identity & Cookies


I have an ASP.NET Core site using AspNetCore.Identity.EntityFrameworkCore 1.1.1 and cookies to authorize/authenticate my users. No matter what I choose as my setting in the code below, the cookie expires after about 20 minutes and I can't figure why. The website will then no longer work unless you close the browser and clear the history/cookies. Any ideas?

services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
    //  Require a confirmed email in order to log in
    config.SignIn.RequireConfirmedEmail = true;
})
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

app.UseIdentity();

//  Add cookie middleware to the configure an identity request and persist it to a cookie.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "Cookie",
    LoginPath = new PathString("/Account/Login/"),
    AccessDeniedPath = new PathString("/Account/Forbidden/"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(20),
    SlidingExpiration = true,

});

I also have some razor code that controls whether to show the admin menu on the _layout page. This crashes when the cookie expires as the users suddenly has no claims. Is there a better way to handle this?

// If user is admin then show drop down with admin navigation
@if (User.HasClaim(System.Security.Claims.ClaimTypes.Role, "admin"))
{
    <ul class="nav navbar-nav">
        @*etc*@
    </ul>
}

Solution

  • You do not need a separate CookieAuthentication middleware when you are using ASPNET identity. UseIdentity() will do that for you and generate a cookie. You can set the "cookie options" in the AddIdentity block of the application like so:

         services.AddIdentity<ApplicationUser, IdentityRole>(config =>
                {
                    //  Require a confirmed email in order to log in
                    config.SignIn.RequireConfirmedEmail = true;
    
                   // Your Cookie settings
                  config.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(1);
                  config.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
                  config.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOut";
                }).AddEntityFrameworkStores<ApplicationDbContext().AddDefaultTokenProviders();
    

    Also, take a look at https://stackoverflow.com/a/34981457/1137785, it gives a background of this sort of a scenario with a very good explanation.