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
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.
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.