Avoid resetting AccessFailedCount by CheckPasswordSignIn in ASP.Net Identity

48 Views Asked by At

This Is My Program.cs :

//Options For Identity
opt.Lockout.AllowedForNewUsers = true;  //True Bcz I want Active For All Users
opt.Lockout.DefaultLockoutTimeSpan = new TimeSpan(100, 1, 1, 1); //Its Like Ban For Ever
opt.Lockout.MaxFailedAccessAttempts = 10; //Just Admin Can Increase This For Users

And This Is My Login Action For Authentication :

Check Username ->
_signInManager.UserManager.FindByNameAsync(model.Username);
Check Password -> 
_signInManager.CheckPasswordSignInAsync(userId, Password, False) 
//False Because I dont Want Increse AccessFailedCount In database for Wrong Passwords

Now If Admin Want Report a User(UserId) This Will Happen:

_userManager.AccessFailedAsync(UserId); //Its Like Increase +1  AccessFailedCount In DataBase

So Now My expectation is that if the admin reports a user 10 times-> user Will Ban For Ever

But Problem Is This : if user login to my WebApi -> This Method _signInManager.CheckPasswordSignInAsync automatic Will Reset AccessFailedCount to 0 ... :(

How to Avoid resetting AccessFailedCount by This Method After one time Succeeded login user

Please Dont Say Its Not Possible... (at last Give Me New Strategy) my Api Is Ready I need Emergency Help

1

There are 1 best solutions below

2
JustAnotherDev On BEST ANSWER

I don't believe you can avoid resetting this count, however a similar effect can be achieved as follows:

  • Get the AccessFailedAcount from the user object before signing them in
  • Sign the user in
  • Restore the AccessFailedCount to the user object
  • Update the user object via UserManager

I've tested the code below which uses a slightly different sign in method than you, but the principle should be exactly the same.

            //get access failed count
            var signinManager = HttpContext.GetOwinContext().GetUserManager<ApplicationSignInManager>();
            var user = signinManager.UserManager.Find(model.Email,model.Password);
            int AccessFailedCount = user.AccessFailedCount;

            //sign user in.
            var result = signinManager.PasswordSignIn(user.UserName, model.Password, false, shouldLockout: false);
            if (result == SignInStatus.Success)
            {
                //restore access failed count.
                user.AccessFailedCount = AccessFailedCount;
                signinManager.UserManager.Update(user);
                //redirect away from login page.
            }