Persistant Cookies in ASP.NET MVC 6

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:
  1. public void ConfigureServices(IServiceCollection services)    
  2. {  
  3.             // Add Entity Framework services to the services container along  
  4.             // with the necessary data contexts for the application  
  5.             services.AddEntityFramework()  
  6.                     .AddSqlServer()  
  7.                     .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:IdentityConnection:ConnectionString"]))  
  8.                     .AddDbContext<YourOtherContext>(options => options.UseSqlServer(Configuration["Data:DataConnection:ConnectionString"]));  
  9.   
  10.             // Add Identity services to the services container  
  11.             services.AddIdentity<ApplicationUser, IdentityRole>(i => {  
  12.                         i.SecurityStampValidationInterval = TimeSpan.FromDays(7);  
  13.                     })  
  14.                     .AddEntityFrameworkStores<ApplicationDbContext>()                     
  15.                     .AddDefaultTokenProviders();  
  16.   
  17.             // Other stuff omitted for brevity  
  18. }  
You might have noticed after a quick peek at this code what exactly you need to be setting. That's right. The SecurityStampValidationInterval property:
  1. // This will allow you to set the duration / expiration of your  
  2. // authentication token  
  3. 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.


Similar Articles