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

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

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

我正在使用身份进行用户管理和用户控制。目前,每次用户关闭 his/her 浏览器并再次打开应用程序时,他们都需要重新登录。

我想将登录从会话更改为 cookie,该 cookie 在 15 分钟不活动后过期。

这是我添加到 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);
}

正如你在上面看到的,我添加了以下内容

config.SlidingExpiration = true;
config.ExpireTimeSpan = TimeSpan.FromMinutes(15);
config.Cookie.HttpOnly = true;

我期待 ExpireTimeSpan 代码将基于会话的登录转换为基于 cookie 的登录。如果用户处于非活动状态,还需要 15 分钟后的 cookie。 SlidingExpiration 应在每次 HTTP 请求时更新 cookie 过期时间。

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

在深入 ASP.NET 核心身份 数小时后,我终于找到了适合您的解决方案。

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

var result = await _signInManager.PasswordSignInAsync(Email, Password, isPersistent: true, lockoutOnFailure: true);

这里第三个参数是Persistent Cookie。根据Microsoft Documentation

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

对于外部登录:

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

SignInResult signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: true);

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