简体   繁体   English

如何在Asp.Net identity 2中手动检查密码?

[英]How to check password manually in Asp.Net identity 2?

This might actually be more of a conceptual question. 这实际上可能更像是一个概念性问题。 In Asp.Net Identity the PasswordHasher generates a different hash for the same string every time you do: 在Asp.Net Identity中,每次执行时,PasswordHasher都会为同一个字符串生成不同的哈希:

new PasswordHasher.HashPassword("myString");

Now if for some reason I need to manually compare a user's input to the password saved in the database, I will most probably get a different string when I hash the user's entered password, than the one that is stored in the database. 现在,如果由于某种原因我需要手动将用户的输入与数据库中保存的密码进行比较,那么当我散列用户输入的密码时,我很可能会得到一个不同的字符串,而不是存储在数据库中的密码。

Can someone please explain this to me? 有人可以向我解释一下吗? Shouldn't hashing the same string result in the same hash and if not, how does Identity itself realize that two different hashes are in fact the same? 不应该在相同的散列中散列相同的字符串,如果不是,Identity本身如何实现两个不同的散列实际上是相同的?

PasswordHasher generates different hashes each time because it uses salting technique. PasswordHasher每次都会生成不同的哈希值,因为它使用了salting技术。 This technique secure the hashed password against dictionary attacks. 此技术可保护散列密码免受字典攻击。 By the way you could use following code to manually verify the password: 顺便说一下,您可以使用以下代码手动验证密码:

if(PasswordHasher.VerifyHashedPassword("hashedPassword", "password") 
    != PasswordVerificationResult.Failed)
{
    // password is correct 
}
var user = _userManager.Users.SingleOrDefault(p => p.PhoneNumber == model.PhoneNumber);
            if (user == null)
            {
                return RedirectToAction(nameof(Login));
            }

            var result1 = _userManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password);
            if (result1 != PasswordVerificationResult.Success)
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM