forum

home / developersection / forums / how to authenticate a user using asp.net mvc?

How to authenticate a user using ASP.NET MVC?

Sunil Singh 1991 15-Jun-2017

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.


c# mvc4 
Updated on 19-Jun-2017
Sunil Singh

Other


Message
Can you answer this question?

Answer

2 Answers

Liked By