Cookie不会因StartUp.cs设置而过期 [英] Cookie not expiring per StartUp.cs settings

查看:91
本文介绍了Cookie不会因StartUp.cs设置而过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在2天的时间里,我尝试了许多解决方案,但仍然无法使它起作用.我想要的是让用户Cookie在设定的时间后过期

例如用户A登录并进入主页,用户A午休.用户A返回并单击导航栏,然后将其重定向到登录页面.

I have tried a plethora of solutions over the course of 2 days and still have not been able to get this to work. What I want is for a user cookie to expire after a set amount of time

E.g. User A logs in and goes to home page, User A goes for a lunch break. User A comes back and clicks on the nav bar and gets redirected to the login page.

我尝试了AddAuthentication()AddSession()AddCookie()选项中的所有选项,所有选项均具有ExpireTimeSpanCookie.Expiration.似乎没有任何作用.该项目使用 ASP.NET身份,我知道应该在cookie选项之前调用此服务.请在下面查看我当前的StartUp.cs,这是我尝试的最后一件事:

I have tried everything from AddAuthentication(), AddSession() and AddCookie() options all having an ExpireTimeSpan and Cookie.Expiration of my choosing. Nothing seems to work. The project uses ASP.NET Identity and I am aware this service should be called before the cookie options. Please see my current StartUp.cs below, this is the last thing i tried:

public class Startup
    {
        public IConfiguration Configuration { get; }
        public IContainer ApplicationContainer { get; private set; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddIdentity<ApplicationUser, IdentityRole>(config =>
                {
                    config.SignIn.RequireConfirmedEmail = true;
                })
                .AddDefaultTokenProviders()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            //other services e.g. interfaces etc.
            services.AddAuthentication().AddCookie(options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.Expiration = TimeSpan.FromSeconds(60);
                options.LoginPath = "/Account/Login";
                options.LogoutPath = "/Account/Logout";
                options.AccessDeniedPath = "/AccessDenied";
                options.ExpireTimeSpan = TimeSpan.FromSeconds(5);
                options.SlidingExpiration = true;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //services.AddSession();

            var containerBuilder = new ContainerBuilder();
            containerBuilder.Populate(services);
            this.ApplicationContainer = containerBuilder.Build();
            var serviceProvider = new AutofacServiceProvider(this.ApplicationContainer);

            return serviceProvider;
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.ConfigureCustomExceptionMiddleware();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            //app.UseSession();
            app.UseMvc();
        }
    }

推荐答案

以下代码不会影响Identity cookie:

The following code isn't affecting the Identity cookie:

services.AddAuthentication().AddCookie(options => ...);

相反,它添加了一个名为Cookies的新的基于cookie的身份验证方案,并配置了 that .在所有标准的Identity设置中,此方案都未使用,因此对其配置的任何更改都将无效.

Instead, it's adding a new cookie-based authentication scheme, named Cookies, and configuring that. With all the standard Identity setup, this scheme is unused, so any changes to its configuration will have no effect.

Identity使用的主要身份验证方案名为Identity.Application,并在您的示例中注册在AddIdentity<TUser, TRole>方法内部.可以使用 ConfigureApplicationCookie .这是一个示例:

The primary authentication scheme used by Identity is named Identity.Application and is registered inside of the AddIdentity<TUser, TRole> method in your example. This can be configured using ConfigureApplicationCookie. Here's an example:

services.ConfigureApplicationCookie(options => ...);

设置适当的位置后,cookie选项将受到预期的影响,但是要设置具有非会话生存期的cookie,您还需要在对isPersistent设置为true ="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.signinmanager-1.passwordsigninasync?view=aspnetcore-2.2#Microsoft_AspNetCore_Identity_SignInManager_1_PasswordSignInAsync_System_String_System_String_System_String_System_Boolean_System_Boolean_" rel ="nofollow no .这是一个示例:

With that in place, the cookie options will be affected as intended, but in order to set a cookie with a non-session lifetime, you also need to set isPersistent to true inside your call to PasswordSignInAsync. Here's an example:

await signInManager.PasswordSignInAsync(
    someUser, somePassword, isPersistent: true, lockoutOnFailure: someBool);

这篇关于Cookie不会因StartUp.cs设置而过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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