'How to Keep Session Even after Browser is Closed for Persistent Cookie
I am using cookie based authentication and making it persistent when login:
var claims = new List<Claim>()
{
new Claim("UserName", user.UserName)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
var utcNow = DateTime.UtcNow;
var props = new AuthenticationProperties()
{
IsPersistent = true,
IssuedUtc = utcNow,
ExpiresUtc = utcNow.AddMinutes(60)
};
_httpcontext.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props).Wait();
My configuration details:
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Global/AccessDenied";
});
services.AddAuthorization(config =>
{
config.AddPolicy(CommonConstValues.AuthorizationPolicyName, policyBuilder =>
{
policyBuilder.UserRequireCustomClaim(CustomClaimTypes.UserName.ToString());
policyBuilder.UserRequireCustomClaim(ClaimTypes.Uri);
});
});
services.AddHttpContextAccessor();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(Convert.ToDouble(configuration["SessionIdleTimeoutSeconds"]));
options.IOTimeout = Timeout.InfiniteTimeSpan;
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Now after closing and reopening the browser when I browse the application I get the authentication is valid but Session Data is cleared. I can see the Cookie is there but the HttpContext has changed.
How to persist the session too? Did I do anything wrong?
Solution 1:[1]
Sessions are inherently not persisted. In fact the use of a server-side session is not a best practice (security, scalability).
If you were to persist the session-cookie, you would also need to store all the data that you will store in the server-side session in a backend store (database, permanent redis-cache, ...) (and provision to clear out abandoned sessions)
So while not answering your question directly, please reconsider your use case for needing to store the session cookie.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rudi Larno |
