Implement ASP.NET Identity IUserLockoutStore witho

2019-07-21 16:16发布

问题:

I have MVC5 project and I don't have direct access to user database instead I was provided with web services, for example:

bool register (string username, string password, string email) //password is plain text
bool login (string username, string password)

My problem is that I have no idea how to implement IUserPasswordStore because ASP Identity force me to use Hash while I'm not allowed to store hashed password because this web services will be used not just by me.

My UserStore.cs:

public Task<string> GetPasswordHashAsync(TUser user)
{
    //I'm suppose to provide hashed password here, but since I don't have any hashed password stored, I have no idea how to implement this method
    string passwordHash = userTable.GetPassword(user.Id);

    return Task.FromResult<string>(passwordHash);
}

public Task<bool> HasPasswordAsync(TUser user)
{
    var hasPassword = !string.IsNullOrEmpty(userTable.GetPassword(user.Id));

    return Task.FromResult<bool>(Boolean.Parse(hasPassword.ToString()));
}

public Task SetPasswordHashAsync(TUser user, string passwordHash)
{
    //do nothing since I don't need to hash the password

    return Task.FromResult<Object>(null);
}

And I was told not to implement IUserPasswordStore because of this and just either use SignInAsync or override PasswordSignInAsync in SignInManager, this is working fine however I ran into another problem which is I need to lockout user if they failed several login attempt and it is not possible to implement IUserLockoutStore without implement IUserPasswordStore.

回答1:

Found the answer: I create a new class that implements IPasswordHasher ...

public class CustomPasswordHasher : IPasswordHasher
{

    public string HashPassword(string password)
    {
        return password; //return password as is
    }

    public PasswordVerificationResult VerifyHashedPassword(
        string hashedPassword,
        string providedPassword)
    {
        if (hashedPassword.Equals(providedPassword)) {
            return PasswordVerificationResult.Success;
        }
        return PasswordVerificationResult.Failed;
    }
}

... and register it in IdentityConfig:

manager.PasswordHasher = new CustomPasswordHasher();