c# - 如何使用 Core 2.2 中的身份在浏览器关闭 15 分钟后保持 session 事件?

标签 c# asp.net-core identity asp.net-core-2.1 asp.net-core-2.2

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

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

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

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

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

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

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

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

最佳答案

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

转到您的 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);

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

关于c# - 如何使用 Core 2.2 中的身份在浏览器关闭 15 分钟后保持 session 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906813/

相关文章:

c# - 如何在SpreadsheetGear中通过文本查找ColumnPostion?

python - python 中的奇怪结果

server - WSO2 身份服务器身份验证

c# - 使用 streamreader 在文本文件中找到特定的用户条目并在标签中显示第 5 个组件

c# - 数组的大小是否受制于int的上限(2147483647)?

c# - System.TypeCode 枚举中的异常字符串类型代码

c# - Razor Pages - 在所有 OnGet 处理程序之后从基类调用方法

azure - 未找到 react 组件

docker - 如何在没有 visual studio 且没有 docker compose 的情况下使用 docker 复制 csproj 文件?

asp.net-mvc - 数据库中已经有一个名为 'AspNetRoles'的对象