Persistent Cookies in MVC6

A few weeks ago, I found the need to create a persistent cookie within an ASP.NET MVC6 (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.

Note : As MVC6 has not be released yet, this is subject to change, but should work for any projects that are targeting the beta6 release.

Getting to Business in Startup.cs

As with most things in MVC6, just about everything is handled within your Startup.cs file. This file is where you will set up all of your necessary routing, services, dependency injection and more. And setting an expiration for a persistent cookie as it turns out, is 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)
{
            // Add Entity Framework services to the services container along
            // with the necessary data contexts for the application
            services.AddEntityFramework()
                    .AddSqlServer()
                    .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:IdentityConnection:ConnectionString"]))
                    .AddDbContext<YourOtherContext>(options => options.UseSqlServer(Configuration["Data:DataConnection:ConnectionString"]));

            // Add Identity services to the services container
            services.AddIdentity<ApplicationUser, IdentityRole>(i => {
                        i.SecurityStampValidationInterval = TimeSpan.FromDays(7);
                    })
                    .AddEntityFrameworkStores<ApplicationDbContext>()                   
                    .AddDefaultTokenProviders();

            // Other stuff omitted for brevity
}

You should notice after a quick peek at this exactly what you need to be setting. That's right, the SecurityStampValidationInterval property :

// This will allow you to set the duration / expiration of your 
// authentication token
i.SecurityStampValidationInterval = TimeSpan.FromDays(7);

This example would only require the user to re-validate if they had not logged into the application within seven days. You can simply adjust this interval value to suit your needs.