11

I'm having an issue while trying to set the expire time of a cookie in my CookieAuthentication, it seems that ExpireTimeSpan is just ignored and when i get the cookie in the browser it's expire time is set to Session..

I'm using c# 8.0 w/ .NET Core 3.1 and here is my ConfigureService code:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => {
            options.Cookie.Name = "authToken";
            options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
            options.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = (context) =>
                {
                    context.HttpContext.Response.Redirect("https://example.com/test/expired.html");
                    return Task.CompletedTask;
                }
            };
        });
        services.AddControllers();
    }

But that's how i get it

enter image description here

NiceToMytyuk
  • 3,644
  • 3
  • 39
  • 100

4 Answers4

13

options.ExpireTimeSpan = TimeSpan.FromMinutes(120); instructs how long authentication ticket itself is valid.

Controls how much time the authentication ticket stored in the cookie will remain valid from the point it is created The expiration information is stored in the protected cookie ticket. Because of that an expired cookie will be ignored even if it is passed to the server after the browser should have purged it.

This is separate from the value of , which specifies how long the browser will keep the cookie.

Docs

You want to control cookie expiration using Expiration property on Cookie property.

public void ConfigureServices(IServiceCollection services)
{

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => {
        options.Cookie.Name = "authToken";
        /// control cookie expiration
        options.Cookie.Expiration = TimeSpan.FromMinutes(120);
        options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
        options.Events = new CookieAuthenticationEvents()
        {
            OnRedirectToLogin = (context) =>
            {
                context.HttpContext.Response.Redirect("https://example.com/test/expired.html");
                return Task.CompletedTask;
            }
        };
    });
    services.AddControllers();
}

Alternatively, you can set MaxAge property too.

dropoutcoder
  • 2,627
  • 2
  • 14
  • 32
  • 4
    in .NET Core 3.1 `Cookie.Expiration` seems to be obsolete, when i try to set it i just get `OptionsValidationException: Cookie.Expiration is ignored, use ExpireTimeSpan instead.` – NiceToMytyuk May 28 '20 at 12:39
  • 1
    But damn yea MaxAge was the right one to set, thank you mate – NiceToMytyuk May 28 '20 at 12:43
3

I have an application in .net core 3.1 my ConfigureServices looks like this:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
    //options.Cookie = new CookieBuilder() { Name = "EcomAuth" };
    options.LoginPath = "/Account/Login/";
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.LogoutPath = "/Account/Logout";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
});

for some bug, when I set the cookie name the code stops working, so this line is commented out. This is my login action

List<Claim> claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, user.Name, ClaimValueTypes.String),
    new Claim(ClaimTypes.Role, userType.Name, ClaimValueTypes.String),
    new Claim("Idusuario",user.IdUser.ToString(), ClaimValueTypes.String),
};

ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
    AllowRefresh = true,
    ExpiresUtc = DateTime.UtcNow.AddMinutes(120),
    IsPersistent = true,
    RedirectUri = "https://localhost:44318/Account/Logout"
};

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties);

its working fine to me.

  • Even by removing cookie name and by adding ExpiresUtc when the cookie is created nothing changed and the expire time is still set to Session.. – NiceToMytyuk May 28 '20 at 12:41
2

For my new ASP.NET MVC 6 project ExpireTimeSpan doesn't work, but MaxAge works well.

.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{      
    options.Cookie.MaxAge = TimeSpan.FromMinutes(120);
})
neosonne
  • 136
  • 1
  • 4
1

I'm posting this here because it took me ages to find a solution and this post came up a lot in my searches, see my answer here: https://stackoverflow.com/a/74292208/1540766

tappetyclick
  • 472
  • 2
  • 14