ASP.NET Core MVC: setting expiration of identity cookie

71,547

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

For ASP.NET Core 2.0

  services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.Name = "CookieName";
            options.Cookie.Expiration = TimeSpan.FromDays(2);
        });

Solution 5

Try

app.UseIdentity().UseCookieAuthentication(
    new CookieAuthenticationOptions
    {
        ExpireTimeSpan = TimeSpan.FromHours(1)
    }
);
Share:
71,547
severin
Author by

severin

Updated on December 27, 2020

Comments

  • severin
    severin over 3 years

    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 for MVC:

    app.UseIdentity();
    

    How can I extend the lifetime of the cookie?

  • severin
    severin over 8 years
    Thanks, using this I am able to change the name of the cookie using this approach, but even if I set ExpireTimeSpan the lifetime of the auth cookie is set to 'Session'. Any idea why? This is my Startup.cs: github.com/severisv/MyTeam/blob/master/src/MyTeam/Startup.cs I tried disabling Facebook-auth. I am not using https.
  • user1620696
    user1620696 over 8 years
    @fiskeboss I added an edit about what I found out concerning this matter.
  • kernowcode
    kernowcode almost 8 years
    I'm on Core RC1 and it does not seem to work. The PasswordSignInAsync works but does not send an auth cookie in the response
  • Suren
    Suren almost 8 years
    'IsPersistent' was really helpful ;)
  • Pieter van Kampen
    Pieter van Kampen over 7 years
    I tried this, with other options, but it seems to be ignored.
  • Igor Soloydenko
    Igor Soloydenko almost 6 years
    This isn't true anymore. Here's the excerpt from the docs with regards to v2.1 ExpireTimeSpan: The TimeSpan after which the authentication ticket stored inside the cookie expires. ExpireTimeSpan is added to the current time to create the expiration time for the ticket. The ExpiredTimeSpan value always goes into the encrypted AuthTicket verified by the server. It may also go into the Set-Cookie header, but only if IsPersistent is set. To set IsPersistent to true, configure the AuthenticationProperties passed to SignInAsync. The default value of ExpireTimeSpan is 14 days.
  • Igor Soloydenko
    Igor Soloydenko almost 6 years
  • gbjbaanb
    gbjbaanb over 5 years
    I also put options.ExpireTimeSpan = TimeSpan.FromDays(2); - one of them will be right even if MS keeps changing its mind how to do it.
  • jjxtra
    jjxtra about 5 years
    Where do ApplicationUser and IdentityRole come from?
  • Ole K
    Ole K about 5 years
    Guess I followed the instruction from here: docs.microsoft.com/de-de/aspnet/core/migration/…. Most of it is inherited from IdentityUser
  • NickG
    NickG almost 4 years
    There is no app.UseIdentity() in .NET Core 3.1. Is there a modern equivalent of this?
  • ninbit
    ninbit over 3 years
    @user1620696 the 'async' part in SignInAsync matters? Because I'm using SignIn
  • timmi4sa
    timmi4sa over 3 years
    @gbjbaanb options.ExpireTimeSpan is application value stored (and protected) inside the cookie, which browser or attacker won't have access to; whereas options.Cookie.Expiration is a timespan that will be communicated to the browser. Both timestamps usually have to be aligned in order to avoid unexpected expiration.
  • Scott Wilson
    Scott Wilson about 3 years
    And it still doesn't work, it sets the expires attribute of the cookie but sets the Expires header to 1/1/1970.
  • Brian
    Brian about 3 years
    @timmi4sa: It's not that simple. On newer versions of .Net Core, options.Cookie.Expiration actually triggers a configuration exception, warning that it should not be used.
  • alanextar
    alanextar over 2 years
    Checked that in net core 5 default expiration period is 14 days. Expires header in response servers mostly for caching it in browser so it doesn't concern cookie.
  • Ali Poustdouzan
    Ali Poustdouzan over 2 years
    @user1620696 Sorry to say this in comment but i set IsPersistent=false so when user close the browser next time user will should be logout but still after user open the browser the cookie exists and user still login. Any idea how can i do that?