How to get information about the Identity parameter value set MaxFailedAccessAttempts

473 views Asked by At

I use a popular library Microsoft.AspNetCore.Identity, which I configured:

var builder = services.AddIdentity<User, Role>(o =>
            {
                o.Lockout.AllowedForNewUsers = true;
                o.Lockout.MaxFailedAccessAttempts = 3;
            });
            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);

            builder.AddEntityFrameworkStores<RepositoryContext>()
            .AddDefaultTokenProviders();

For now, MaxFailedAccessAttempts is set to 3 tries but may change for the entire application in the future. How can I get this value in Actions? I would like to use the value in action to calculate how many tries are left before the account is locked.

int attemptsLeft = user.AccessFailedCount - UNKNOWN.MaxFailedAccessAttempts;
return Unauthorized($"Wrong password. {attemptsLeft} attempts left.");

The solution that I found is initializing MaxFailedAccessAttempts and getting in action value from appsettings.json, but I don't want to add another field in the configuration.

1

There are 1 answers

1
Farhad Zamani On BEST ANSWER

You can inject UserManager and get MaxFailedAccessAttempts from Options.Lockout.MaxFailedAccessAttempts

private readonly UserManager<User> _userManager;
public UserController(UserManager<User> userManager)
{
    _userManager = userManager;
}
.
.
.
int maxFailedAccessAttempts = _userManager.Options.Lockout.MaxFailedAccessAttempts;
int attemptsLeft = maxFailedAccessAttempts - user.AccessFailedCount;
return Unauthorized($"Wrong password. {attemptsLeft} attempts left.");