如何获取有关 Identity 参数值集 MaxFailedAccessAttempts 的信息

How to get information about the Identity parameter value set MaxFailedAccessAttempts

我使用一个流行的库 Microsoft.AspNetCore.Identity,我配置了它:

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();

目前,MaxFailedAccessAttempts 设置为 3 次尝试,但将来可能会针对整个应用程序进行更改。如何在 Actions 中获取此值?我想使用行动中的值来计算在帐户被锁定之前还剩下多少次尝试。

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

我找到的解决方案是初始化 MaxFailedAccessAttempts 并从 appsettings.json 获取操作值,但我不想在配置中添加另一个字段。

您可以注入 UserManager 并从 Options.Lockout.MaxFailedAccessAttempts

获取 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.");