【问题标题】:ASP.NET Core 1.0 - MVC 6 - Cookie ExpirationASP.NET Core 1.0 - MVC 6 - Cookie 过期
【发布时间】:2016-05-20 14:12:24
【问题描述】:

更新:

这绝对不是 RC1 中的错误。 cookie 设置与默认的 UserManager 和 UserStore 一起使用,所以它必须与我的 UserManager/UserStore 相关,我已经监督了。我基本上在这里使用实现: https://github.com/jesblit/ASPNET5-FormAuthenticationLDAP

原帖:

我遇到了持久登录问题。无论我如何配置 cookie,30 分钟后,用户都会自动注销(无论用户与应用程序交互多少)。

我设置了我的应用程序:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCaching();
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromDays(1);
            options.CookieName = ".MySessionCookieName";
        });

        services.AddEntityFramework()
            .AddNpgsql()
            .AddDbContext<Model1>(options =>
                options.UseNpgsql(Configuration["Data:DefaultConnection:ConnectionString"]));

        services.AddIdentity<MinervaUser, MinervaRole>(options => {
            options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(1);
            options.Cookies.ApplicationCookie.SlidingExpiration = true;
            options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;

        })
            .AddUserStore<MinervaUserStore<MinervaUser>>()
            .AddRoleStore<MinervaRoleStore<MinervaRole>>()
            .AddUserManager<MinervaUserManager>();

        services.AddMvc();
    }

还有:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");

            try
            {
                using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                    .CreateScope())
                {

                }
            }
            catch { }
        }
        app.UseIISPlatformHandler(options => { options.AuthenticationDescriptions.Clear(); options.AutomaticAuthentication = true; });
        app.UseSession();
        app.UseIdentity();
        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

登录操作是:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {

                _logger.LogInformation(1, "User logged in.");
                return RedirectToLocal(returnUrl);
            }
...

我正在使用默认的 SignInManager。如前所述,我在 Startup.Configure 和 Startup.ConfigureServices 中设置的 Expiration Timeouts 完全没有效果。登录 -> 30 分钟 -> 自动注销 :(

如何延长这段时间?

(顺便说一句:自定义 User、UserManager、UserStore 不会以任何方式干扰 Cookie,它们“只是”验证凭据(它们应该做什么;)))

【问题讨论】:

  • 您使用的似乎是 RC1 或更早版本。我认为这不值得尝试,因为它可能是 Microsoft 的错误。我会更新到 RC2 看看会发生什么。

标签: asp.net cookies asp.net-core-mvc asp.net-core-1.0


【解决方案1】:

TL;DR:如果您有自定义用户管理器,请务必实现 GetSecurityStampAsync、UpdateSecurityStampAsync 并将 SupportsUserSecurityStamp 设置为 true。


解决方案非常简单(但我在文档中的任何地方都没有找到)。由于默认实现(创建新的 ASP MVC6 应用程序...)有效,我检查了他们的数据库表并找到了安全标记(我没有实现)。根据这个问题的答案What is ASP.NET Identity's IUserSecurityStampStore<TUser> interface?,这个邮票每 30 分钟重新验证一次,这非常适合我的问题。所以,我所做的只是扩展我自己的 UserManager

public class MinervaUserManager:UserManager<MinervaUser> 
// Minerva being the name of the project
{
...
    public override bool SupportsUserSecurityStamp
    {
        get
        {
            return true;
        }
    }
   public override async Task<string> GetSecurityStampAsync(MinervaUser user)
    {
        // Todo: Implement something useful here!
        return "Token";
    }

    public override async Task<IdentityResult> UpdateSecurityStampAsync(MinervaUser user)
    {
        // Todo: Implement something useful here!
        return IdentityResult.Success;
    }

这些假人总是在每次更新时返回相同的 SecurityStamp 和“Success”。这与完全没有 SecurityStamps 可以防止注销一样安全。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 2018-05-02
    • 2017-09-26
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多