I need to implement the feature as Users should remain logged in until they choose to log out manually.
I had tried this in Program.cs
for session:
builder.Services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60); // Set session timeout to 60 minutes or your desired duration
options.Cookie.HttpOnly = true; // Ensure the session cookie is accessible only through HTTP
options.Cookie.IsEssential = true; // Make the session cookie essential
});
I need to implement the feature as Users should remain logged in until they choose to log out manually.
I had tried this in Program.cs
for session:
builder.Services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60); // Set session timeout to 60 minutes or your desired duration
options.Cookie.HttpOnly = true; // Ensure the session cookie is accessible only through HTTP
options.Cookie.IsEssential = true; // Make the session cookie essential
});
Share
Improve this question
edited Jan 20 at 8:17
DarkBee
15.7k8 gold badges70 silver badges114 bronze badges
asked Jan 20 at 4:18
Sachin TripathiSachin Tripathi
12 bronze badges
1 Answer
Reset to default 0Doing this
builder.Services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60); // Set session timeout to 60 minutes or your desired duration
options.Cookie.HttpOnly = true; // Ensure the session cookie is accessible only through HTTP
options.Cookie.IsEssential = true; // Make the session cookie essential
});
Has nothing to do the user login.
You have to different expiretime to take care of. The cookie it self and the content of the cookie by controlling the ExpiresUtc.
You can specify the lifetime of the user authentication ticket, stored inside the cookie:
public class AccountController : Controller
{
public async Task<IActionResult> Login()
{
// Example user claims
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "[email protected]"),
new Claim(ClaimTypes.Role, "Administrator")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
// Configure authentication properties
var authProperties = new AuthenticationProperties
{
IsPersistent = true, // Keeps the cookie across browser sessions
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) // Set cookie expiration
};
// Sign in the user
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return Redirect("/");
}
}
Then, you can control the lifetime of the cookie itself here
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(60); // Default expiration time
options.SlidingExpiration = true; // Renew cookie if active within ExpireTimeSpan
});