A few weeks ago, I found the need to create a persistent cookie within an ASP.NET MVC 6 (colloquially known as "vNext") and nothing seemed to pop out when trying to figure this out. So, I thought I would share this with everyone.
Getting to business in Startup.cs
As with the most things in MVC6, just about everything is handled within your Startup.cs file. This is the file where you will set up all your necessary routing, services, dependency injection, and more. And setting an expiration for a persistent cookie, turns out to be no different.
To set your persistent cookie expiration, you'll need to associate the cookie to your current Identity provider. This is handled within the ConfigureServices method of the previously mentioned Startup.cs file, as seen below:
- public void ConfigureServices(IServiceCollection services)
- {
-
-
- services.AddEntityFramework()
- .AddSqlServer()
- .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:IdentityConnection:ConnectionString"]))
- .AddDbContext<YourOtherContext>(options => options.UseSqlServer(Configuration["Data:DataConnection:ConnectionString"]));
-
-
- services.AddIdentity<ApplicationUser, IdentityRole>(i => {
- i.SecurityStampValidationInterval = TimeSpan.FromDays(7);
- })
- .AddEntityFrameworkStores<ApplicationDbContext>()
- .AddDefaultTokenProviders();
-
-
- }
You might have noticed after a quick peek at this code what exactly you need to be setting. That's right. The SecurityStampValidationInterval property:
-
-
- i.SecurityStampValidationInterval = TimeSpan.FromDays(7);
This example would only require the users to re-validate if they have not logged into the application within seven days. You can simply adjust this interval value to suit your needs.