11

I'm trying to set the validateInterval for an ASP.NET 5 RC1 application which makes use of ASP.NET Identity 3

I am trying to implement the code in this answer.

there are many code sample like this answer but it seems it isn't valid in ASP.NET 5 RC1

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

If I try use the above code example in ASP.NET 5 RC1 I can't as

Provider is not a property of CookieAuthenticationOptions and Visual studio cannot locate CookieAuthenticationProvider in any namespace via its lightbulb options.

How do I set the validateInterval in ASP.NET 5 RC1?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
greay
  • 1,725
  • 5
  • 18
  • 37

2 Answers2

9

The validation interval is set in IdentityOptions:

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

You can attach to the validation event using the CookieAuthenticationEvents:

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

As of ASP.NET Core 2.0 you won't be able to set SecurityStampValidationInterval when you AddIdentity.

You'll be able to set the ValidationInterval via SecurityStampValidatorOptions:

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

P.S: You'll have to AddIdentity first and ConfigureApplicationCookie after.

Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54
  • 2
    Works in ASP.NET Core 6. A small sidenote. I had overwritten the CookieAuthenticationEvents in CookieAuthenticationOptions with new CookieAuthenticationEvents and as a result SecurityStamp validation was not performed anymore, because OnValidatePrincipal is registered in AddIdentity. So make sure not to set a new CookieEvents instance, but rather assign specific Funcs if required. Took me a while... ;( – Diego Frehner Jun 03 '22 at 12:13