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.