User-462241089 posted
I noticed that my auth cookie is not dying after 1 hour, like it should.
//in startup.cs
. . .
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Login/UserLogin";
options.Cookie.IsEssential = true;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
});
//in login controller
. . .
HttpContext.Session.SetString("UserName", user.username);
var role = GetUserRole(user);
//Code copied from
//https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.username),
new Claim("username", user.username),
new Claim(ClaimTypes.Role, role),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
AllowRefresh = false,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
IsPersistent = false
};
I think this might be because I have my session set to close after one hour, too.
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(3600);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Now, I use the session to display the current logged in user's username on my webapp, so I need to have the session to last for the one hour a user is allowed to stay logged in.
string name = HttpContextAccessor.HttpContext.Session.GetString("UserName");
. . .
<h3>@name</h3>
Their log in is handled with cookie authentication, of course. However, I just noticed this problem in my app. It is taking two hours after logging in to see my cookie expire, and after one hour, I see my user's username disappear from the app page (indicating
that the session has closed).
Is my assumption correct? Is the cookie not starting it's timeout countdown until the session is closed?
Is it possible to set my cookie the delete if the session closes? I need them both to close after one hour.