forum

Home / DeveloperSection / Forums / How to authenticate a user using ASP.NET MVC?

How to authenticate a user using ASP.NET MVC?

Sunil Singh171815-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
{
  
        publicclassUsers
        {
            publicint Id { get; set; }
            publicstring userName { get; set; }
            publicstring userPassword { get; set; }
           
 
 
            publicclassUsersDBContext : DbContext
            {
                public DbSet<Users> Users { get; set; }
            }
 
 
           }
}

  controller code

namespace Testing.Controllers
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
 
        private Users.UsersDBContext db = new Users.UsersDBContext();
 
        // GET: /Users/   
        publicActionResult Index()
        {
            return View();
        }
 
        [HttpPost]
        publicActionResult 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.


Updated on 19-Jun-2017

Can you answer this question?


Answer

2 Answers

Liked By