简体   繁体   English

如何使用ASP.NET MVC对用户进行身份验证?

[英]How authenticate a user using ASP.NET MVC?

I'm creating a web app with .net using a login for users. 我正在使用.net使用用户登录名创建一个Web应用程序。 After registration the users' data is stored in my local SQL database and the user must be able to log in using these. 注册后,用户的数据将存储在我的本地SQL数据库中,并且用户必须能够使用这些数据登录。

Currently I've managed to register users and they can log in when I use a hard coded password and user name but I can't figure out how I can check the user's given credentials and the ones in the database to check if these match. 目前,我已经设法注册了用户,当我使用硬编码的密码和用户名时,他们可以登录,但是我不知道如何检查用户的给定凭据以及数据库中的凭据以检查它们是否匹配。

I did extensive research but didn't find a proper solution but surprisingly could not come up with a working solution. 我进行了广泛的研究,但未找到合适的解决方案,但令人惊讶的是无法提出有效的解决方案。

Here is my current code: 这是我当前的代码:

My users model: 我的用户模型:

namespace Models
{
    public class Users
    {
        public int Id { get; set; }
        public string userName { get; set; }
        public string userPassword { get; set; }
        public string userEmail { get; set; }
        public string userCompany { get; set; }


        public class UsersDBContext : DbContext
        {
            public DbSet<Users> Users { get; set; }
        }


    }
}

My controller 我的控制器

namespace Eindwerk.Controllers
{
    public class UsersController : Controller
    {
        private Users.UsersDBContext db = new Users.UsersDBContext();

        // GET: /Users/    
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Users users)
        {
            if (ModelState.IsValid)
            {
                if(users.userName == "NAAM" && users.userPassword == "WACHTWOORD")
                {
                    FormsAuthentication.SetAuthCookie(users.userName, false);
                    return RedirectToAction("", "Home");
                }
                {
                    ModelState.AddModelError("", "Invalid username and/or password");
                }
            }

            return View();
        }

My View 我的观点

@model Eindwerk.Models.Users

@{
    ViewBag.Title = "Login";
    Layout = "../_Login.cshtml";

}
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <div class="panel-body">
    <fieldset>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.userName, new { @class = "form-control", Value="Username"})
            @Html.ValidationMessageFor(model => model.userName)
        </div>
                <br />
        <div class="editor-field">
            @Html.TextBoxFor(model => model.userPassword, new { @class = "form-control", Value= "Password"  })
            @Html.ValidationMessageFor(model => model.userPassword)
        </div>
        <br />
        <br />
        <p>
            <input type="submit" value="SIGN IN" class="btn btn-outline btn-primary btn-lg btn-block"/>
        </p>

    </fieldset>
        </div>
}

So instead of using if(users.userName == "NAAM" && users.userPassword == "WACHTWOORD") I want to check properly if the user is valid and registered in my database or not so I can grant or deny access. 因此,我不想使用if(users.userName == "NAAM" && users.userPassword == "WACHTWOORD")而是要正确检查用户是否有效并在我的数据库中注册,因此可以授予或拒绝访问权限。

Anybody a proper solution? 有人合适的解决方案吗? Or link to decent documentation in order to resolve this issue? 还是链接到体面的文档以解决此问题?

Any help is really appreciated! 任何帮助都非常感谢!

You need to reference the db.Users collection. 您需要引用db.Users集合。

[HttpPost]
public ActionResult Index(Users users)
{
        if (ModelState.IsValid)
        {
            var hash = GenerateHash(users.userPassword,Settings.Default.salt);
            var authUser = db.Users.FirstOrDefault(row => row.userName == users.userName && row.userPassword == hash )
            if ( authUser != null )
            {
                Session["role"] = authUser.Role;

                FormsAuthentication.SetAuthCookie(users.userName, false);
                return RedirectToAction("", "Home");
            }
            else 
            {
                ModelState.AddModelError("", "Invalid username and/or password");
            }
        }

        return View();
}

private static string GenerateHash(string value, string salt)
{
    byte[] data = System.Text.Encoding.ASCII.GetBytes(salt + value);
    data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
    return Convert.ToBase64String(data);
}

See MD5 hash with salt for keeping password in DB in C# for a more indepth discussion of salting and hashing. 请参阅带有Salt的MD5哈希以在C#中将密码保存在DB中 ,以获取关于Salting和哈希的更深入讨论。 Note that I'm assuming you have a Settings class with the salt value. 请注意,我假设您有一个带有Salt值的Settings类。 You can replace this with another mechanism for retrieving the salt. 您可以用另一种盐回收机制代替它。

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

相关问题 使用身份验证 ASP.NET MVC 中的用户 - Authenticate user in ASP.NET MVC with identities 如何在ASP.NET中验证用户 - How to Authenticate user in ASP.NET ASP.NET MVC 身份验证 - ASP.NET MVC Authenticate 如何使用AspNet.Identity使用Asp.Net MVC5 RTM位登录/验证用户? - How do you login/authenticate a user with Asp.Net MVC5 RTM bits using AspNet.Identity? 在Asp.Net MVC中验证自定义用户类 - Authenticate custom user class in Asp.Net MVC 如何在成为旧版ASP.NET MVC应用程序的一部分时对Web API 2中的用户进行身份验证? - How to authenticate user in Web API 2 when being part of a legacy ASP.NET MVC application? Facebook .NET SDK:如何使用ASP.NET MVC 2进行身份验证 - Facebook .NET SDK: How to authenticate with ASP.NET MVC 2 如何从控制台应用程序在 ASP.NET MVC 应用程序中进行身份验证 - How to authenticate in an ASP.NET MVC application from a console application ASP.NET MVC - 如何检测用户是否使用屏幕阅读器 - ASP.NET MVC - How to detect if user is using a screen reader 如何使用ASP.NET MVC实现自动用户登录 - How to implement auto user login using asp.net mvc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM