【问题标题】:How to set asp.net Identity cookies expires time如何设置asp.net身份cookie过期时间
【发布时间】:2020-10-14 20:05:59
【问题描述】:

我使用 Asp.Net Identity 来控制我的应用程序的授权。现在,我需要这样做:如果用户在 30 分钟内没有操作,则跳转到登录页面,当他登录时没有选择“isPersistent”复选框。 并且,如果他选择了“isPersistent”复选框,则将 cookie 的过期日期设置为 14 天。 我尝试通过像这样更改 Startup.Auth.cs 来做到这一点:

public void ConfigureAuth(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        SlidingExpiration = true,
        CookieName = WebHelpers.ConstStrings.AUTHCOOKIESNAME
    });
}

和这样的登录代码:

private async Task SignInAsync(User user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    if (isPersistent)
    {
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }
    else
    {
        AuthenticationManager.SignIn(new AuthenticationProperties() { ExpiresUtc = new DateTimeOffset(DateTime.UtcNow.AddMinutes(30)) }, identity);
    }
}

但我发现当用户没有选择isPersistent复选框时,cookies的过期日期已经是'Session',而不是当前时间加上30分钟。

使用类似之后的代码时的cookie状态,因此“记住我”复选框不起作用。:(。

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = TimeSpan.FromMinutes(30),
            SlidingExpiration = true,
            CookieName = WebHelpers.ConstStrings.AUTHCOOKIESNAME
        });

【问题讨论】:

    标签: c# asp.net cookies asp.net-identity


    【解决方案1】:

    如果AuthenticationPropertiesIsPersistent 属性设置为false,则cookie 过期时间设置为Session。

    如果复选框“记住我”被选中,那么AuthenticationManager.SignIn(new AuthenticationProperties{ IsPersistent = true }, userIdentity); 将创建一个cookie,其过期时间等于您在Startup.cs 中设置的ExpireTimeSpan(默认至 14 天)。

    如果复选框“记住我”是未选中,那么您必须使用AuthenticationManager.SignIn(new AuthenticationProperties{ IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30)}, userIdentity);。再次将IsPersistent 设置为true,但现在我们为ExpiresUtc 赋予一个值,因此它不会使用来自CookieAuthenticationOptionsStartup.cs

    public override async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
    {
        var userIdentity = await CreateUserIdentityAsync(user).WithCurrentCulture();
        // Clear any partial cookies from external or two factor partial sign ins
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
        if (rememberBrowser)
        {
            var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id));
            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity, rememberBrowserIdentity);
        }
        else
        {
            //AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity);
            if (isPersistent)
            {
                AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, userIdentity);
            }
            else
            {
                AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) }, userIdentity);
            }        
        }
    }
    

    【讨论】:

    • 完美,我用你的代码实现了上面的功能,谢谢。另外,我把Owin从2.1.0版本升级到3.0.1。
    • 这适用于哪个版本的 ASP.NET Identity?我在默认的 ASP.NET MVC 5 模板上使用 2.2.2 并登录我有以下行 var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent: false, shouldLockout: false); 并且没有 ExpiresUtc 或任何其他方式来设置它。
    • 还想知道如何在较新版本的 ASP.NET Identity 中实现这一点......
    • @phxism:请看下面我的回答
    【解决方案2】:

    使用这个...

    public void ConfigureAuth(IAppBuilder app)
    {
      app.UseCookieAuthentication(new CookieAuthenticationOptions
      {
          ExpireTimeSpan = TimeSpan.FromHours(1),
      });            
    }
    

    【讨论】:

    • 谢谢,但我发现如果我设置了这个属性,“记住我”将无法工作。
    • 这对我不起作用。它仍然默认为 14 天。
    • @NabeelZafar 感谢您的帮助,但我在下面发布了对我有用的答案。
    【解决方案3】:

    为了实现您在 ASP.NET Core 3.1 中描述的功能,我在Startup 中配置身份验证的方式如下:

            services.ConfigureApplicationCookie(o =>
            {
                ...
                o.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                o.SlidingExpiration = true;
                ...
                o.Events.OnSigningIn = ctx =>
                {
                    if (ctx.Properties.IsPersistent)
                    {
                        var issued = ctx.Properties.IssuedUtc ?? DateTimeOffset.UtcNow;
                        ctx.Properties.ExpiresUtc = issued.AddDays(14);
                    }
                    return Task.FromResult(0);
                };
            });
    

    使用OnSigningIn 回调,如果单击“isPersistent”复选框,我将过期日期明确设置为现在 + 14 天。

    【讨论】:

    • 完美运行!使用身份验证事件比覆盖身份登录操作要容易得多。
    【解决方案4】:

    我遇到了同样的问题,这段代码对我有用(在 Startup.cs 文件中)..

    services.Configure<IdentityOptions>(options =>
    {
        options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(3650);
    });
    

    这会使持久性 cookie 增加大约 10 年

    注意:如果您希望缩短到期时间,您可以使用 TimeSpan.FromMinutes(1); 1 分钟或 TimeSpan.FromSeconds(30); 30 秒等。

    【讨论】:

    • 如果您将过期时间设置为晚于2038,某些浏览器可能会提前过期 cookie。
    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 2019-11-13
    • 2021-08-03
    • 2017-03-06
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多