Question

I'm creating a web app with .net using a login for users. After registration the users' data is stored in my local SQL database and the user must be able to log in using these.

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.

Anybody a proper solution? Or link to decent documentation in order to resolve this issue?

Any help is really appreciated!

Was it helpful?

Solution

You need to reference the db.Users collection.

[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. Note that I'm assuming you have a Settings class with the salt value. You can replace this with another mechanism for retrieving the salt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top