ASP.net Identity UserManager不验证密码

时间:2016-03-23 16:16:06

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

我正在设置一个asp.net web api 2应用程序,我在自定义Identity.UserManager验证用户密码时遇到问题。当我尝试验证用户的哈希密码时,它总是返回失败!即使我知道我提供了正确的密码。在这里,我试图验证用户并将令牌返回给该用户。用户数据表(DVUsers)存储在MySQL数据库中。我怀疑我的问题与密码哈希如何存储在mysql中有关。

从一开始,我的授权服务器Proivder:

public class AuthServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        try
        {
            AuthContext _ctx = new AuthContext();
            DVUserManager userManager = new DVUserManager(_ctx);
            AuthRepo _repo = new AuthRepo(userManager, _ctx);

            DVUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);
        }
        catch (Exception ex)
        {
            context.SetError("invalid_grant", "message");
        }
    }
}

现在这是我的AuthRepo类。 VerifyHashedPsssword总是在FindUser方法中返回失败。

public class AuthRepo : IDisposable
{
    private AuthContext _ctx;
    private DVUserManager _userManager;

    public AuthRepo(DVUserManager userManager, AuthContext ctx)
    {
        _ctx = ctx;
        _userManager = userManager;
    }

    public async Task<IdentityResult> RegisterUser(DVUser user)
    {
        DVUser iuser = new DVUser { UserName = user.UserName};

        var result = await _userManager.CreateAsync(iuser, user.UserName);
        return result;
    }
    public async Task<DVUser> FindUser(string userName, string Password)
    {
        //Find the user works fine, it finds the correct user
        DVUser user = await _userManager.FindByNameAsync(userName);

        //compare passwords. VerifyHasedPAssword ALWAYS is returning failed
        PasswordVerificationResult result = _userManager.PasswordHasher.VerifyHashedPassword(user.Password, Password);

        if (result == PasswordVerificationResult.Success) { return user; }
        else { return null; }
    }

    public void Dispose()
    {
        _ctx.Dispose();
        _userManager.Dispose();
    }
}

您可能也希望看到我的支持课程。

public class AuthContext : IdentityDbContext<IdentityUser>
{
    public AuthContext() : base("localhost") //name of the data connection to use
    {

    }
    public DbSet<DVUser> DVUsers { get; set; }
}

我的自定义用户管理器

public class DVUserManager : UserManager<DVUser>
{
    public DVUserManager(AuthContext ctx) : base(new DVUserStore(ctx))
    {
        PasswordValidator = new MinimumLengthValidator(4);
    }
}

这是实现IUser的DVUser

public class DVUser : IUser
{
    public string Id
    {
        get; set;
    }

    public string UserName
    {
        get; set;
    }

    public string Password { get; set; }

    public int DVClientID { get; set; }
}

最后是我的客户UserStore

public class DVUserStore : IUserStore<DVUser>, IUserPasswordStore<DVUser>
{
    AuthContext _context;
    public DVUserStore(AuthContext context)
    {
        _context = context;
    }

    public Task CreateAsync(DVUser user)
    {
        user.Id = Guid.NewGuid().ToString();
        _context.DVUsers.Add(user);
        return _context.SaveChangesAsync();
    }

    public Task DeleteAsync(DVUser user)
    {
        throw new NotImplementedException();
    }

    public void Dispose()
    {
        _context.Dispose();
    }

    public Task<DVUser> FindByIdAsync(string userId)
    {
        throw new NotImplementedException();
    }

    public Task<DVUser> FindByNameAsync(string userName)
    {
        Task<DVUser> task = _context.DVUsers.Where(
                    apu => apu.UserName == userName)
                    .FirstOrDefaultAsync();

        return task;
    }

    public Task<string> GetPasswordHashAsync(DVUser user)
    {
        if (user == null)
        {
            throw new ArgumentNullException("user");
        }

        return Task.FromResult(user.Password);
    }

    public Task<bool> HasPasswordAsync(DVUser user)
    {
        return Task.FromResult(user.Password != null);
    }

    public Task SetPasswordHashAsync(DVUser user, string passwordHash)
    {
        return Task.FromResult(user.Password = passwordHash);
    }

    public Task UpdateAsync(DVUser user)
    {
        throw new NotImplementedException();
    }
}

MySQL表,DVUsers看起来像这样。 DVUsers Table, UTF8 encoding

以下是DVUsers中的数据。只有一个用户 DVUsers table data

感谢您的帮助!!

1 个答案:

答案 0 :(得分:1)

我找到了解决方案!有两个问题。首先,我是个白痴。在此行中查看AuthRepo类中的Register User方法:
var result = await _userManager.CreateAsync(iuser,user.UserName); 我将用户密码设置为USERNAME,而不是我的表单发送的密码...哦,天啊..

第二个问题!我发现它仍然没有用。我发现如果将密码列数据类型设置为二进制(68),密码哈希将被正确存储。最后的工作。我希望我能帮助别人!