使用Core 2.2中的Identity关闭浏览器15分钟后如何使会话保持活动状态?

Jun*_*ior 6 c# identity asp.net-core asp.net-core-2.1 asp.net-core-2.2

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

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

我想将会话中的登录更改为在15分钟处于非活动状态后过期的cookie.

这是我添加到Startup类的内容

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);
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我添加了以下内容

config.SlidingExpiration = true;
config.ExpireTimeSpan = TimeSpan.FromMinutes(15);
config.Cookie.HttpOnly = true;
Run Code Online (Sandbox Code Playgroud)

我期待ExpireTimeSpan代码将基于会话的登录转换为基于cookie的.如果用户处于非活动状态,也会在15分钟后期待cookie.本SlidingExpiration应更新每个HTTP请求Cookie的到期时间.

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

Tan*_*jel 4

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

转到您的Loginpost 方法并按_signInManager.PasswordSignInAsync如下方式编写您的方法:

var result = await _signInManager.PasswordSignInAsync(Email, Password, isPersistent: true, lockoutOnFailure: true);
Run Code Online (Sandbox Code Playgroud)

这里的第三个参数是持久性Cookie。根据微软文档

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

对于外部登录:

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

SignInResult signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: true);
Run Code Online (Sandbox Code Playgroud)

我已经在我身边测试过了,效果非常好!