Identity Framework用户锁定

时间:2016-04-06 09:36:26

标签: c# asp.net asp.net-web-api2 asp.net-identity 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;

之后我通过POST /api/Account/Register注册新用户(默认为scaffolded AccountController)。帐户已创建,LockoutEnabled属性设置为true。但是,如果我尝试使用错误的密码登录过POST /Token几次,则帐户不会被锁定。

我也对/Token端点的实现感兴趣。是AccountController GET api/Account/ExternalLogin吗?我在那里设置了断点,但当我尝试登录时,执行没有停在那里。

我错过了什么?

1 个答案:

答案 0 :(得分:4)

如果您使用的是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授权(资源所有者凭据)登录的用户。如果您还想禁止锁定用户使用其他授权登录,则必须覆盖其他方法(GrantAuthorizationCodeGrantRefreshToken等),检查await userManager.IsLockedOutAsync(user.Id)是否为真方法也是如此。

相关问题