Asp.Net 5 Authentication cookie is reset after every rebuild – How can I truly persist it?

I have a problem with an Asp.Net 5 application I’m currently developing. Essentially it’s an anonymous page with user-attached data, so I’m very much dependant on having a persistent and reliable cookie to identify a calling user. Therefore, I have also checked how I need to configure cookies, and put them on a very long expiration timespan, and made them persistent.

Here is my code:

In my Startup.cs:

        .AddCookie(options =>
            options.Events.OnRedirectToLogin = context =>
                context.Response.StatusCode = 401;
                return Task.CompletedTask;

            options.ExpireTimeSpan = TimeSpan.FromDays(100 * 365);
            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.Cookie.MaxAge = TimeSpan.FromDays(100 * 365);
            options.Cookie.SameSite = _webHostEnvironment.IsDevelopment() ? SameSiteMode.None : SameSiteMode.Strict;
            options.Cookie.Name = Configuration["IdentificationCookieName"];

Obviously I also included the required calls in the Configure method:


In the controller for setting the cookie, I’m using the following code:

var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, callerId.ToString()));

var principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync(
    new AuthenticationProperties()
          IsPersistent = true,
          ExpiresUtc = DateTime.UtcNow.AddYears(100),
          AllowRefresh = true,

Where am I going wrong here? This seems to occur after every rebuild.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Thanks to Roar S.’s comment which pointed me in the right direction, I was able to figure out the problem:

The key point – my application is running in a container, which is restarted on rebuild. The culprit is indeed the data protection section – All cookie encryption keys stored on the machine are also regenerated when the container restarts.

Therefore it is required to setup the .AddDataProtection section to either use a cloud-based storage, or a simple file mount for local development.

This is what I ended up using:

In my docker-compose file, I added a mount:

  - ./Keys/Storage:/keys/storage

And in my startup script:

if (IsDevelopmentEnvironment())
         .PersistKeysToFileSystem(new DirectoryInfo("/keys/storage"));

Now the cookies are stable.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x