ASP.NET Core MVC: setting expiration of identity cookie

前端 未结 6 515
死守一世寂寞
死守一世寂寞 2020-12-04 18:15

In my ASP.NET Core MVC app the lifetime of the authentication cookie is set to \'Session\', so it lasts until I close the browser. I use the default authentication scheme fo

相关标签:
6条回答
  • 2020-12-04 18:18

    For ASP.NET Core 2.0

      services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name = "CookieName";
                options.Cookie.Expiration = TimeSpan.FromDays(2);
            });
    
    0 讨论(0)
  • 2020-12-04 18:23

    There's an answer for version 2.0 but it didn't work for me. I had to do:

    services.ConfigureApplicationCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromDays(30);
    });
    

    The default value is 14 days.

    0 讨论(0)
  • 2020-12-04 18:23

    Try

    app.UseIdentity().UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
            ExpireTimeSpan = TimeSpan.FromHours(1)
        }
    );
    
    0 讨论(0)
  • 2020-12-04 18:24

    For some reason I had the issue when using SignInAsync([..], true) the cookie was never be shown in browser (and properly the login failed):

    So, I tried adding the UTC timezone difference into the TimeSpan of ExpireTimeSpan

    services.AddIdentity<ApplicationUser, IdentityRole>(o =>
    {
        // add TimeSpan with 5 minutes plus timezone difference from Utc time
        o.Cookies.ApplicationCookie.ExpireTimeSpan = DateTime.Now.Subtract(DateTime.UtcNow).Add( TimeSpan.FromMinutes(5) );
    
    });
    

    Voila! It worked and the cookie is shown with +5min expiration only in browser.

    PingBack to github.com https://github.com/aspnet/Identity/issues/766#issuecomment-253237576

    0 讨论(0)
  • 2020-12-04 18:36

    The ASP.NET Identity middleware which you are using is a wraper around some calls to UseCookieAuthentication which includes the Cookie Authentication middleware on the pipeline. This can be seen on the source code for the builder extensions of the Identity middleware here on GitHub. In that case the options needed to configure how the underlying Cookie Authentication should work are encapsulated on the IdentityOptions and configured when setting up dependency injection.

    Indeed, looking at the source code I linked to you can see that the following is run when you call app.UseIdentity():

    var options = app.ApplicationServices.GetRequiredService<IOptions<IdentityOptions>>().Value;
    app.UseCookieAuthentication(options.Cookies.ExternalCookie);
    app.UseCookieAuthentication(options.Cookies.TwoFactorRememberMeCookie);
    app.UseCookieAuthentication(options.Cookies.TwoFactorUserIdCookie);
    app.UseCookieAuthentication(options.Cookies.ApplicationCookie);
    return app;
    

    To setup the IdentityOptions class, the AddIdentity<TUser, TRole> method has one overloaded version which allows to configure the options with one lambda. Thus you just have to pass in a lambda to configure the options. In that case you just access the Cookies properties of the options class and configure the ApplicationCookie as desired. To change the time span you do something like

    services.AddIdentity<ApplicationUser, IdentityRole>(options => {
    
        options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(1);
    
    });
    

    EDIT: The ExpireTimeSpan property is only used if when calling HttpContext.Authentication.SignInAsync we pass in an instance of AuthenticationProperties with IsPersistent set to true.

    Trying out just with the Cookie Authentication Middleware it turns out that this works: if we just sign in without this option, we get a cookie that lasts for the session, if we send this together we get a cookie which lasts what we setup when configuring the middleware.

    With ASP.NET Identity the way to do is pass the parameter isPersistent of the PasswordSignInAsync with value true. This ends up being a call to SignInAsync of the HttpContext passing in the AuthenticationProperties with the IsPersistent set to true. The call ends up being something like:

    var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
    

    Where the RememberMe is what configures if we are setting IsPersistent to true or false.

    0 讨论(0)
  • 2020-12-04 18:43

    In ASP.NET Core 2.0 use ExpireTimeSpan property instead of Cookie.Expiration.

    services.ConfigureApplicationCookie(options =>
    {   
        options.Cookie.Name = "CookieName";         
        options.ExpireTimeSpan = TimeSpan.FromHours(24);
        options.SlidingExpiration = true;               
    });
    

    From docs:

    Cookie.Expiration: Gets or sets the lifespan of a cookie. Currently, this option no-ops and will become obsolete in ASP.NET Core 2.1+. Use the ExpireTimeSpan option to set cookie expiration.

    0 讨论(0)
提交回复
热议问题