我尝试在 3 次登录尝试失败后锁定用户登录 5 分钟。我已将这 3 行添加到App_Start/IdentityConfig.cs
public static ApplicationUserManager Create( ... )
method:
manager.MaxFailedAccessAttemptsBeforeLockout = 3;
manager.DefaultAccountLockoutTimeSpan = new TimeSpan(0, 5, 0);
manager.UserLockoutEnabledByDefault = true;
之后我通过注册新用户POST /api/Account/Register
(在默认脚手架中AccountController
)。帐户已创建并且LockoutEnabled
属性设置为true
。但如果我尝试通过以下方式登录POST /Token
密码错误几次,帐户不会被锁定。
我也感兴趣在哪里实施/Token
端点。是否在AccountController
GET api/Account/ExternalLogin
。我在那里设置了断点,但当我尝试登录时,执行并没有停止。
我缺少什么?
如果您使用 Visual Studio 中的默认 Web API 模板,则必须更改GrantResourceOwnerCredentials
的方法ApplicationOAuthProvider
类(在 Web API 项目的 Provider 文件夹中找到)。像这样的东西可以让您跟踪失败的登录尝试,并阻止锁定的用户登录:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await userManager.FindByNameAsync(context.UserName);
if (user == null)
{
context.SetError("invalid_grant", "Wrong username or password."); //user not found
return;
}
if (await userManager.IsLockedOutAsync(user.Id))
{
context.SetError("locked_out", "User is locked out");
return;
}
var check = await userManager.CheckPasswordAsync(user, context.Password);
if (!check)
{
await userManager.AccessFailedAsync(user.Id);
context.SetError("invalid_grant", "Wrong username or password."); //wrong password
return;
}
await userManager.ResetAccessFailedCountAsync(user.Id);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
请注意,这样您只能锁定尝试使用以下方式登录的用户password
grant(资源所有者凭证)。如果您还想禁止锁定的用户使用其他授权登录,则必须覆盖其他方法(GrantAuthorizationCode
, GrantRefreshToken
等),检查是否await userManager.IsLockedOutAsync(user.Id)
这些方法也是如此。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)