We are using simple cookie authentication in a ASP.Net Core webapp. The login has worked for almost 3 months now. Then suddenly, a problem started appearing.
This is how I setup authentication in Startup.cs:
private void ConfigureAuthentication(IServiceCollection services)
{
var configurationService = services.BuildServiceProvider().GetRequiredService<IConfigurationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.LoginPath = "/Identity/Login";
options.AccessDeniedPath = "/Identity/AccessDenied";
options.ExpireTimeSpan = TimeSpan.FromMinutes(double.Parse(configurationService.Get("CookieTimeout").Result.Value));
options.LogoutPath = "/Identity/Logout";
});
services.AddAuthorization(options =>
{
options.AddPolicy("KeyUsers",
authBuilder =>
{
authBuilder.RequireRole("KeyUsers");
});
options.AddPolicy("Admins",
authBuilder =>
{
authBuilder.RequireRole("Admins");
});
options.AddPolicy("Users",
authBuilder =>
{
authBuilder.RequireRole("Users");
});
});
}
Here is how I actually log in:
var role = await _roleRepository.Read(user.RoleId);
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()),
new Claim(ClaimTypes.Email, user.EmailAddress),
new Claim(ClaimTypes.Name, user.CWID),
new Claim(ClaimTypes.Role, role.Description)
};
ClaimsIdentity userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await httpContext.SignInAsync(principal);
_logger.LogInformation("A user with the following cwid entered the correct password: {0}", cwid);
user.FailedLoginAttempts = 0;
await _userRepository.Update(user);
return LoginResult.Successful;
So basically, after the user entered the correct credentials, I log them in using the above code. They should then be redirected to a landing page for logged in users. This has worked fine for 2-3 months but now, for some reason, when they get to the landing page, they are immediately redirected again to the login page, meaning that they are not actually logged in. Strangely, I only have this problem on one browser (new Edge), when I try it using another (Chrome), it works. So I think that there must be something wrong with how the authentication cookie is set in the browser but I am not sure. Any ideas what is going on here?