How to authenticate a user using ASP.NET MVC?

Total Post:45

Points:323
Mvc4 
C#
 939  View(s)
Ratings:
Rate this:

On creating a web app using .net with a login for users.  The users' data is stored in my local SQL database after registration and the user ise able to log in using these.

 I've correctly coded to register users and they are able to log in when I use a hard coded password and user name but I am not able to check the user's given credentials and the ones in the database to crosscheck the same.

I have tried the following code: 

 

namespace Testing.Models
{
  
        public class Users
        {
            public int Id { get; set; }
            public string userName { get; set; }
            public string userPassword { get; set; }
           
 
 
            public class UsersDBContext : DbContext
            {
                public DbSet<Users> Users { get; set; }
            }
 
 
           }
}

  controller code

namespace Testing.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        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 == "UserName" && users.userPassword == "Password")
                {
                    FormsAuthentication.SetAuthCookie(users.userName, false);
                    return RedirectToAction("", "Home");
                }
                {
                    ModelState.AddModelError("", "Invalid username and/or password");
                }
            }
 
            return View();
        }
    }
}

So instead of using if(users.userName == "UserName" && users.userPassword == "Password")

 I want to check properly if the user isn't  unauthorized and registered as per the database or not so that I should permit it or not.

  1. Post:1

    Points:7
    Re: How to authenticate a user using ASP.NET MVC?

    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);

    }

     

     Online Shopping Bags for Women | Buy Wall Decor Art & Trays Online in India | buy women bags at best price in india | buy designer woman purses | online shopping for women handbags | buy designer tote bags

  1. Post:19

    Points:135
    Re: How to authenticate a user using ASP.NET MVC?

         You can use this 

         [Authorize]
            public ActionResult About()
            {
                return View();//This view is viewed by authenticated user only
            }
            [HttpPost]
            public ActionResult SignIn(Login Model)
            {
               
                var context = new TestEntities2();
                var data = context.Logins.ToList();
                var valid = context.Logins.Count(x => x.UserName.Equals(Model.UserName,       StringComparison.OrdinalIgnoreCase) && x.Password.Equals(Model.Password));
     
                if (valid > 0)
                {
                    FormsAuthentication.SetAuthCookie(Model.UserName, true);
                   
                    return  View("About");
                }
                else
                {
                    ViewBag.error = "Incorrect User Name Password!!!";
                    return View("SignIn");
     
     
                }
     
            }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!