I have a ASP.NET Core 2.0 MVC application which authenticates using an API. The API will return a JWT value if successful, the user will then be signed in and the token value stored in a secure cookie (and used in further requests).
However, if the user signs in, closes a tab and waits for a short while, they will be prompted to log in again (though they will still have an auth cookie). When they log in again the site will successfully sign in, but then redirect to the login page again. If the user at this point navigates to an authorised page, they will be allowed (which is correct). It's like the initial RedirectToAction hasn't registered that the user is authorised yet, but on subsequent requests it works fine.
I believe the prompt to login is due to the app pool refreshing on IIS due to inactivity. So - two questions
- Can I avoid having to reauthenticate users on application pool refresh?
- Why isn't the application recognising the first redirect is authenticated?
I've found a possible related post here https://github.com/aspnet/Security/issues/356, though this seems to be about OIDC. Worth noting that this is not an issue in another near identical site which is using ASP.NET Core Identity.
Cookie settings:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/Account/Login/";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromHours(6);
});
Sign in code:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.Email),
new Claim("AuthToken", response.Result.Token)
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync();
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity));
_logger.LogInformation("{0} logged in.", model.Email);
if (String.IsNullOrWhiteSpace(returnUrl))
{
return RedirectToAction("Index", "Home");
}
return Redirect(returnUrl);