【问题标题】:Identity Framework User Lockdown身份框架用户锁定
【发布时间】:2016-07-26 14:54:48
【问题描述】:

我尝试在 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(默认脚手架AccountController)注册新用户。帐户已创建,LockoutEnabled 属性设置为 true。但是如果我尝试通过POST /Token 登录几次,密码错误,帐户不会被锁定。

我也很感兴趣/Token 端点的实现在哪里。是在AccountControllerGET api/Account/ExternalLogin。我在那里设置了断点,但是当我尝试登录时执行并没有停止。

我错过了什么?

【问题讨论】:

    标签: c# asp.net asp.net-web-api2 asp.net-identity asp.net-identity-2


    【解决方案1】:

    如果您使用 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);
    }
    

    请注意,这种方式只能锁定尝试使用password 授权(资源所有者凭据)登录的用户。如果您还想禁止被锁定的用户使用其他授权登录,则必须覆盖其他方法(GrantAuthorizationCodeGrantRefreshToken 等),并检查这些方法中的 await userManager.IsLockedOutAsync(user.Id) 是否为真。

    【讨论】:

    • 不客气。我刚刚编辑了答案,我忘记在用户成功登录后重置失败的访问计数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2018-02-12
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多