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:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.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:
app.UseAuthentication();
app.UseAuthorization();
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(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties()
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddYears(100),
AllowRefresh = true,
}
);
Where am I going wrong here? This seems to occur after every rebuild.
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:
volumes:
- ./Keys/Storage:/keys/storage
And in my startup script:
if (IsDevelopmentEnvironment())
{
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("/keys/storage"));
}
Now the cookies are stable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.