Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the session alive after the browser is closed for 15 minutes using Identity in Core 2.2?

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?

like image 438
Junior Avatar asked Dec 23 '18 20:12

Junior


People also ask

How check session expired in ASP.NET Core?

You can check the HttpContext. Current. User. Identity.

What does HttpContext SignInAsync do?

SignInAsync(HttpContext, String, ClaimsPrincipal, AuthenticationProperties) Sign in a principal for the specified scheme.

What is CookieAuthenticationDefaults AuthenticationScheme?

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.


1 Answers

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.

For External Login:

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!

like image 95
TanvirArjel Avatar answered Sep 30 '22 14:09

TanvirArjel