1

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!

Sebastian
  • 6,293
  • 6
  • 34
  • 47
user3629755
  • 81
  • 3
  • 14

1 Answers1

1

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.

Community
  • 1
  • 1
B2K
  • 2,541
  • 1
  • 22
  • 34
  • Nice, thanks a lot B2K! Been looking for that all day! – user3629755 May 12 '14 at 19:21
  • A side question tough: I want to use 3 roles (Admin, user and editor), how do you give these roles to those registered users? – user3629755 May 12 '14 at 19:23
  • 4
    Please please please, hash and salt your passwords. the password should **never** exist in your database in plain text! – arserbin3 May 12 '14 at 19:45
  • @user3629755 Just add another field to Users for the role, and store the role in the user's session. Editing my answer above. – B2K May 12 '14 at 21:26
  • @mason So, you come along 6 months late to the party and your only contribution is to down vote my response? There is already even a comment on the original question suggesting that the user investigate using a more robust authentication scheme. I happen to agree with all three of you on that point. I'll edit my post to demonstrate how to use a one-way encryption scheme. Please remove the down vote. – B2K Oct 21 '14 at 16:47