使用Core 2.2中的Identity,在关闭浏览器15分钟后如何保持会话活动? [英] How to keep the session alive after the browser is closed for 15 minutes using Identity in Core 2.2?

查看:60
本文介绍了使用Core 2.2中的Identity,在关闭浏览器15分钟后如何保持会话活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET Core 2.2框架的顶部有一个使用C#编写的应用程序.

I have an application written using C# on the top of ASP.NET Core 2.2 framework.

我正在使用Identity进行用户管理和用户控制.当前,每次用户关闭浏览器并再次打开应用程序时,都要求他们重新登录.

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.

我想将登录名从会话更改为cookie,该cookie在闲置15分钟后就会过期.

I want to change the login from a session into a cookie that expired after 15 minutes of being inactive.

这是我添加到Startup类中的内容

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;

我希望ExpireTimeSpan代码将基于会话的登录名转换为基于cookie的代码.如果用户处于非活动状态,则在15分钟后还需要cookie. SlidingExpiration应该在每个HTTP请求中更新cookie的失效时间.

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.

如何将基于会话的登录名转换为基于Cookie的登录名?

How can I convert my session-based login to cookie-based?

推荐答案

在研究了 ASP.NET Core身份几个小时之后,我终于找到了适合您的解决方案.

After digging into the ASP.NET Core identity for hours, finally I have found the solution for you.

转到您的Login post方法并按如下所示编写您的_signInManager.PasswordSignInAsync方法:

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);

这是持久性Cookie的第三个参数.根据 Microsoft文档

Here is the third parameter is for Persistent Cookie. According to Microsoft Documentation

IsPersistent标志,指示登录cookie在浏览器关闭后是否应保留.

IsPersistent Flag indicating whether the sign-in cookie should persist after the browser is closed.

对于外部登录:

转到您的ExternalLoginCallback方法并按如下所示编写您的_signInManager.ExternalLoginSignInAsync方法:

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!

这篇关于使用Core 2.2中的Identity,在关闭浏览器15分钟后如何保持会话活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆