Search code examples
c#asp.net-coreasp.net-core-identity

How exactly PasswordSignInAsync() and MaxFailedAccessAttempts connect?


So, the method SignInManager.PasswordSignInAsync has a last parameter lockoutOnFailure which when true, locks out the user if they enter wrong credentials. But there is already a property called MaxFailedAccessAttempts which locks out a user after (by default) 5 successful events.

I am somewhat confused here, and could not find an answer to how this method works exactly based on the 4th parameter. Why do we need to set the lockoutOnFailure if there is already an option set for when to lock out? I don't want to set it to true.

How I understand it works:

If lockoutOnFailure: true, then even if it is the first attempt of the user to sign in, should they enter wrong credentials, they get locked out. If lockoutOnFailure: false, then even if it is their 5th attempt, should they enter wrong credentials, they won't be locked out. I don't want neither of this to happen, so I don't want to set it to either value. What should I do? Or do I understand the method wrong?


Solution

  • ASP.NET Core Identity is open source, means you can easily look into the code. The PasswordSignInAsync ultimatively calls CheckPasswordSignInAsync method.

    Which does

    if (UserManager.SupportsUserLockout && lockoutOnFailure)
    {
        // If lockout is requested, increment access failed count which might lock out the user
        await UserManager.AccessFailedAsync(user);
        if (await UserManager.IsLockedOutAsync(user))
        {
            return await LockedOut(user);
        }
    }
    

    This means, the MaxFailedAccessAttempts maybe set globally, but its not checked unless the sign in methods are called with lockoutOnFailure.

    The Docs already note that, but its phrased a bit odd:

    Gets or sets the number of failed access attempts allowed before a user is locked out, assuming lock out is enabled. Defaults to 5.

    The lockoutOnFailure parameter is that enabling mechanism. Which the docs of PasswordSignInAsync make clear.

    Flag indicating if the user account should be locked if the sign in fails.

    If the flag is set to false, then failed attempts won't increase the failed sign-in counter.

    However, once the account is locked, PasswordSignInAsync will returned LockedOut result, even when lockedOnFailure is set to false. This parameter only determins if the counter will be increased on failure (and once exceeding flagging the account as locked).