如何检查我的登录操作中是否存在用户

本文关键字:操作 是否 存在 用户 登录 我的 何检查 检查 | 更新日期: 2023-09-27 18:37:05

我开始使用新的身份管理,并且有一个简单的需求。当我的用户使用错误的名称登录时,它会报告密码错误。我如何更改它,以便它还使用 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);
    }

如何检查我的登录操作中是否存在用户

我做到了:

        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");
        }
这是一个

坏主意

如果您要验证用户名并报告用户名不存在,则允许潜在的黑客轻松确定通过网站注册的用户名。

返回给用户的实际错误消息是 (ASPNET.标识 v1):

Invalid username or password

否则,如上所述,您可以通过以下方式检查具有给定用户名的用户是否存在:

var user = await UserManager.FindByNameAsync(username);
我相信

这篇文章是 如何让我的 MVC5 ASP.NET 身份登录操作检查用户名是否存在?

解决此问题的一种方法是在数据库中查找以查看用户是否存在 - 类似于 -> if(myUserRepository.GetUserByUserName(model.UserName) != null) *User exists*

还应该有一个UserManager.FindByName(model。用户名)方法,可以做同样的事情

但更重要的是,你确定要这样做吗?如果您给出一条错误消息,指出用户名错误,则黑客有机会找到有效的用户名。然后,他们可以运行脚本来尝试您网站上的所有用户名,并获取有效用户名的列表。