Reputation: 4583
Recently I created my new website in .net core 2.0 and I'm using a persistent cookie in authentication. I'm also using persistent culture cookie for language.
my website hosted in azure shared pool and I didn't specify any machine key.
Problem. When I re-open my website after few hours of inactivity (new browser) I lost my auth cookie and I need to log in again but culture cookie works as per the last session.
I also setup Application Insights availability to keep warm up my application (ping website in every 10 min from 2 different location).
LoginController
if (this.accountService.ValidateOTP(phoneNumber, otp))
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.MobilePhone, phoneNumber),
new Claim(ClaimTypes.Name, phoneNumber)
};
var userIdentity = new ClaimsIdentity("Custom");
userIdentity.AddClaims(claims);
ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);
//await HttpContext.SignOutAsync("AnimalHubInstance");
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
userPrincipal,
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.Now.AddYears(1),
});
}
Startup
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(option =>
{
option.LoginPath = new PathString("/Account/Unauthorized");
option.LogoutPath = new PathString("/Account/Logout");
option.Cookie.Name = ".myAuth";
option.ExpireTimeSpan = TimeSpan.FromDays(365);
option.Cookie.Expiration = TimeSpan.FromDays(365);
});
Upvotes: 0
Views: 1112
Reputation: 18465
When I re-open my website after few hours of inactivity (new browser) I lost my auth cookie and I need to log in again but culture cookie works as per the last session.
The value of your culture cookie is just urlencoded. As Tseng said that the machine key for hashing and encryption may automatically re-generate at some points. I assumed that this issue caused by the pricing tier you chose. For Free and Shared tier, you application would run on shared infrastructure and you only have the limited resources(e.g. CPU time, RAM, disk space) and no SLA.
Moreover, I tried to restart the website and recycle the application pool on my local side, the authentication cookie could still work as expected. For my web app hosting under the basic pricing tier, I do not encounter this issue until now.
Upvotes: 1
Reputation: 64259
You need to use the data protection to persist your session encryption keys.
When hosting apps in Azure App Service or IIS in general (in VM or on-premises), IIS will recycle apps and app pools on inactivity. So if your app doesn't get hit for a specific amount of time, it will be shut down and started again on next connection.
When this happens, new encryption keys will be generated for session and your previous session will be invalid.
Upvotes: 1