I have an application written using C#
on the top of ASP.NET Core 2.2 framework.
I am using Identity to user management and user control. Currently, everytime a user closed his/her browser and open the app again, they are required to log in again.
I want to change the login from a session into a cookie that expired after 15 minutes of being inactive.
Here is what I have added to the Startup class
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<User()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication()
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// This code should be executed after the identity id registered to work
services.ConfigureApplicationCookie(config =>
{
config.SlidingExpiration = true;
config.ExpireTimeSpan = TimeSpan.FromMinutes(15);
config.Cookie.HttpOnly = true;
config.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api", StringComparison.CurrentCultureIgnoreCase))
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
}
return Task.FromResult(0);
}
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
As you can see above, I added the following
config.SlidingExpiration = true;
config.ExpireTimeSpan = TimeSpan.FromMinutes(15);
config.Cookie.HttpOnly = true;
I am expecting the ExpireTimeSpan
code to convert my session-based login to cookie-based. Also expecting the cookie after 15 minutes if the user is inactive. The SlidingExpiration
should update the cookie expiry time on every HTTP request.
How can I convert my session-based login to cookie-based?
You can check the HttpContext. Current. User. Identity.
SignInAsync(HttpContext, String, ClaimsPrincipal, AuthenticationProperties) Sign in a principal for the specified scheme.
The CookieAuthenticationDefaults. AuthenticationScheme GitHub Source shows it's set to "Cookies" . The authentication cookie's IsEssential property is set to true by default. Authentication cookies are allowed when a site visitor hasn't consented to data collection.
After digging into the ASP.NET Core identity for hours, finally I have found the solution for you.
Go to your Login
post method and write your _signInManager.PasswordSignInAsync
method as follows:
var result = await _signInManager.PasswordSignInAsync(Email, Password, isPersistent: true, lockoutOnFailure: true);
Here is the third parameter is for Persistent Cookie. According to Microsoft Documentation
IsPersistent
Flag indicating whether the sign-in cookie should persist after the browser is closed.
Go to your ExternalLoginCallback
method and write your _signInManager.ExternalLoginSignInAsync
method as follows:
SignInResult signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: true);
I have tested it in my side and it works perfectly!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With