Search code examples
asp.net-coreasp.net-identity-3

ASP.Net Core SignInManager lockoutOnFailure


ASP.Net Core has SignInManager which handles user authentication. One of the methods is PasswordSignInAsync(string username, string password, bool isPersistent, bool lockoutOnFailure). Setting lockoutOnFailure to true should temporarily lock out the user after a certain number of failed login attempts.

Looking at the AspNetUsers table in the database I see the following:

  • AccessFailedCount increase by 1 for each failed access, when it hits 5 it rolls over to 0.
  • Upon rolling over to 0 LockoutTimeEnd is set to 5 minutes into the future.
  • LockoutEnabled however remains 0 even after rollover, and user can continue attempting to log in.

It looks like the intended functionality is to allow 5 login attempts, then lock out the account for 5 minutes.

So my questions are are:

  1. How do I set number of allowed failed logins?
  2. How do I set the lockout period?
  3. Why doesn't the lockout trigger?

Solution

    1. How do I set number of allowed failed logins?
    2. How do I set the lockout period?

    Default project template uses an extension method for configuring identity services AddIdentity<TUser, TRole> (in Startup class ConfigureServices method). There is an overload of this method that you can configure IdentityOptions.

    Instead of

    services.AddIdentity<ApplicationUser, IdentityRole>()
         .AddEntityFrameworkStores<ApplicationDbContext>()
         .AddDefaultTokenProviders();
    

    You can use

    var lockoutOptions = new LockoutOptions()
    {
         AllowedForNewUsers = true,
         DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5),
         MaxFailedAccessAttempts = 5
    };
    
    services.AddIdentity<ApplicationUser, IdentityRole>(options =>
         {
             options.Lockout = lockoutOptions;
         })
         .AddEntityFrameworkStores<ApplicationDbContext>()
         .AddDefaultTokenProviders();
    

    The above is pointeless because these are the default values of LockoutOptions, but you can changes them as you like.