如何在ASP.NET Core中设置cookie validateInterval?

时间:2016-05-19 09:43:56

标签: asp.net-core asp.net-identity asp.net-core-mvc asp.net-identity-3

我试图为使用validateInterval的ASP.NET 5 RC1应用程序设置ASP.NET Identity 3

我正在尝试在this回答中实现代码。

有许多代码示例,例如this answer,但它似乎在ASP.NET 5 RC1中无效

  app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(15)
            },
            ExpireTimeSpan = TimeSpan.FromMinutes(30)
        });

如果我尝试在ASP.NET 5 RC1中使用上述代码示例,我就不能

Provider不是CookieAuthenticationOptions的属性 并且Visual Studio无法通过其灯泡选项在任何命名空间中找到CookieAuthenticationProvider

如何在validateInterval中设置ASP.NET 5 RC1

2 个答案:

答案 0 :(得分:5)

验证间隔在IdentityOptions中设置:

services.AddIdentity<AppUser, AppRole>(options =>
{
    options.SecurityStampValidationInterval = TimeSpan.FromMinutes(15);
}

您可以使用CookieAuthenticationEvents附加到验证事件:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    Events = new CookieAuthenticationEvents()
    {
        OnValidatePrincipal = context =>
        {
            Microsoft.AspNet.Identity.SecurityStampValidator.ValidatePrincipalAsync(context);
            return Task.FromResult(0);
        },
    },
    ExpireTimeSpan = TimeSpan.FromMinutes(30)
});

答案 1 :(得分:1)

从ASP.NET Core 2.0开始,您SecurityStampValidationInterval时将无法设置AddIdentity

您可以通过ValidationInterval设置SecurityStampValidatorOptions

        services.Configure<SecurityStampValidatorOptions>(options =>
        {
            options.ValidationInterval = TimeSpan.FromSeconds(10);
        });

P.S:您必须先AddIdentity,然后再ConfigureApplicationCookie