我开始使用新的身份管理并且有一个简单的需求。当我的用户使用错误的名称登录时,它会报告密码错误。如何更改此设置以便它还使用dbcontext方法检查用户名是否存在?
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
// Validate the password
IdentityResult result = IdentityManager.Authentication.CheckPasswordAndSignIn(AuthenticationManager, model.UserName, model.Password, model.RememberMe);
if (result.Success)
{
return Redirect("~/home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
答案 0 :(得分:13)
我这样做了:
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
if (UserManager.FindByName("Admin") == null)
{
var user = new ApplicationUser() { UserName = "Admin" };
UserManager.Create(user, "Admin123");
UserManager.AddToRole(user.Id, "Admin");
}
答案 1 :(得分:7)
这是个坏主意
如果您要验证用户名并报告用户名不存在,则允许潜在的黑客轻松确定通过网站注册的用户名。
返回给用户的实际错误消息是(ASPNET.Identity v1):
Invalid username or password
否则,如详细说明,您可以通过以下方式检查具有给定用户名的用户是否存在:
var user = await UserManager.FindByNameAsync(username);
答案 2 :(得分:0)
我认为这篇文章与 How can I make my MVC5 ASP.NET Identity login action check if a user name exists?
重复解决此问题的一种方法是在数据库中查找是否存在用户 - 例如 - &gt;
if(myUserRepository.GetUserByUserName(model.UserName) != null) *User exists*
还应该有一个UserManager.FindByName(model.UserName)方法可以做同样的事情
但更重要的是,你确定要这样做吗?如果您指定用户名错误的错误消息,则黑客有机会找到有效的用户名。然后,他们可以运行尝试您网站上所有用户名的脚本,并获取有效用户名列表。