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

允我心安 提交于 2020-04-10 16:48:02

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/53906813/how-to-keep-the-session-alive-after-the-browser-is-closed-for-15-minutes-using-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!