我使用一个流行的库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.");