Mat*_*Mav 3 c# asp.net asp.net-identity asp.net-web-api2 asp.net-identity-2
我试图在 3 次登录尝试失败 5 分钟后锁定用户登录。我已将这 3 行添加到App_Start/IdentityConfig.cs public static ApplicationUserManager Create( ... )方法中:
manager.MaxFailedAccessAttemptsBeforeLockout = 3;
manager.DefaultAccountLockoutTimeSpan = new TimeSpan(0, 5, 0);
manager.UserLockoutEnabledByDefault = true;
Run Code Online (Sandbox Code Playgroud)
之后,我通过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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,通过这种方式,您只能锁定尝试使用password授权(资源所有者凭据)登录的用户。如果你也想使用其他补助会禁止锁定用户登录,你必须覆盖其他的方法(GrantAuthorizationCode,GrantRefreshToken等),检查是否await userManager.IsLockedOutAsync(user.Id)是这些方法真的太。
| 归档时间: |
|
| 查看次数: |
1548 次 |
| 最近记录: |