身份框架用户锁定
作者:互联网
3次尝试登录失败5分钟后,我试图锁定用户登录.我已经将这3行添加到App_Start / IdentityConfig.cs公共静态ApplicationUserManager Create(…)方法中:
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模板,则必须更改ApplicationOAuthProvider类的GrantResourceOwnerCredentials方法的行为(位于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);
}
请注意,通过这种方式,您只能锁定尝试使用密码授予(资源所有者凭据)登录的用户.如果您还想禁止锁定的用户使用其他授权登录,则必须重写其他方法(GrantAuthorizationCode,GrantRefreshToken等),并检查await userManager.IsLockedOutAsync(user.Id)在这些方法中是否也是如此.
标签:asp-net-web-api2,asp-net-identity,asp-net-identity-2,asp-net,c 来源: https://codeday.me/bug/20191027/1942348.html