ASP.NET 1.0的核心 - MVC 6 - Cookie有效期 [英] ASP.NET Core 1.0 - MVC 6 - Cookie Expiration

查看:794
本文介绍了ASP.NET 1.0的核心 - MVC 6 - Cookie有效期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:

这绝对不是在RC1的错误。该cookie设置与默认的UserManager和UserStore工作,所以它必须是事涉及到我的UserManager / UserStore,我监督。我基本上是在这里使用的实现:
https://github.com/jesblit/ASPNET5-FormAuthenticationLDAP

It is definitely not a bug in RC1. The cookie settings are working with the default UserManager and UserStore, so it must be something related to my UserManager/UserStore, I've overseen. I basically use the implementation here: https://github.com/jesblit/ASPNET5-FormAuthenticationLDAP

原贴:

我有持续登录的问题。不管我怎么配置的cookie,30分钟后,该用户将自动注销(不管用户多少与应用程序交互)。

I have a problem with persistent logins. No matter how I configure the cookie, after 30 minutes, the User is automatically logged out (no matter how much the user interacts with the App).

我安装我的应用程序:

    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没有任何效果可言。登录 - > 30分钟 - >自动注销:(

I am using the default SignInManager. As said, the Expiration Timeouts I set in Startup.Configure and Startup.ConfigureServices have no effect at all. Login -> 30mins -> automatically logged out :(

怎样做才能延长这个时间段?

What to do to extend this time period?

(BTW:自定义用户,的UserManager,UserStore不以任何方式德饼干干扰,他们只是验证凭据(他们应该是什么;)))

(btw: the custom User, UserManager, UserStore don't interfere with teh Cookie in any way, they "just" validate the credentials (what they're supposed to ;) ))

推荐答案

TL; DR:如果您有一个自定义的用户管理器时,一定要落实GetSecurityStampAsync,UpdateSecurityStampAsync并设置SupportsUserSecurityStamp为true

TL;DR: If you have a custom user manager, be sure to implement GetSecurityStampAsync, UpdateSecurityStampAsync and set SupportsUserSecurityStamp to true.

解决这个问题的解决方案是pretty简单(但我没有在文档中发现的任何地方)。作为默认实现(创建新的ASP应用MVC6 ...)的作品,我检查自己的数据库表,发现安全标志(我没有实现)。根据该回答这个问题<一href=\"https://stackoverflow.com/questions/19487322/what-is-asp-net-identitys-iusersecuritystampstoretuser-interface\">What是ASP.NET身份的IUserSecurityStampStore&LT;&TUSER GT;接口?这邮票每30分钟,这令人惊讶的适合我的问题重新验证。所以,我所做的只是延长我自己的UserManager以

The solution to this is pretty simple (but I haven't found it anywhere in the docs). As the default implementation (Create new ASP MVC6 App...) works, I checked their DB tables and found the security stamp (which I didn't implement). According to the Answer to this question What is ASP.NET Identity's IUserSecurityStampStore<TUser> interface? this stamp is revalidated every 30 minutes, which surprisingly fits to my problem. So, all I did was extending my own UserManager with

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和成功。这是因为没有在所有位prevents注销的SecurityStamps安全。

These dummies always return the same SecurityStamp and "Success" on every Update. This is as secure as not having the SecurityStamps at all bit prevents the logout.

这篇关于ASP.NET 1.0的核心 - MVC 6 - Cookie有效期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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