2014-07-26 55 views
4

我尝试使用此代码增加AccessFailedCount,但它不工作(在AspNetUsers表中不增加AccessFailed计数)。 =>在这段代码中,我的第一反应是,当用户登录失败,所以递增AccessFailed计数,但没有工作的代码,所以请给我建议更新代码和任何事情。如何在ASP.net Identity 2.0上启用AccessFailedCount和Lockout功能?

   var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); 

       // find user by username first 
       var user = manager.FindByName(txtUserName.Text); 

       if (user != null) 
       { 
         var validCredentials = manager.Find(txtUserName.Text, txtPassword.Text); 

         // When a user is lockedout, this check is done to ensure that even if the credentials are valid 
         // the user can not login until the lockout duration has passed 
         if (manager.IsLockedOut(user.Id)) 
         { 
         error message; 
         } 

         // if user is subject to lockouts and the credentials are invalid 
         // record the failure and check if user is lockedout and display message, otherwise, 
         // display the number of attempts remaining before lockout 
         else if (manager.GetLockoutEnabled(user.Id) && validCredentials == null && manager.SupportsUserLockout) 
         { 
          // Record the failure which also may cause the user to be locked out 
          manager.AccessFailed(user.Id); 

          if (manager.IsLockedOut(user.Id)) 
          { 
           error message; 
          } 
          else 
          { 
           int accessFailedCount = manager.GetAccessFailedCount(user.Id); 

          } 

         } 
         else 
         { 

            IdentityHelper.SignIn(manager, user, RememberMe.Checked); 

            // When token is verified correctly, clear the access failed count used for lockout 
            manager.ResetAccessFailedCount(user.Id); 
            Response.Redirect("/Home.aspx", false); 

         } 

        } 

回答

1

您可能想要查看ASP.NET Identity Framework 2.1中的SignInManager类。 查看此博客文章的更多信息ASP.NET Identity 2.1.0-alpha1

SignInManager简化了认证,帐户锁定和双因素认证验证过程,直至单个方法调用。

SignInStatus result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, true); 

然后,您可以像这样响应登录结果。

switch (result) 
{ 
    case SignInStatus.Success: 
     // Login success 
    case SignInStatus.LockedOut: 
     // Account locked out 
    case SignInStatus.RequiresVerification: 
     // Do two factor verification 
    case SignInStatus.Failure: 
    default: 
     // Login failure 
}