MVC custom login authentication

断了今生、忘了曾经 提交于 2021-02-10 15:13:59

问题


Hi I'm developing an app in MVC and I have a problem with login, I want to know how can I manage the login depending on the user role.

While the moment the login works fine but I need to identify the role user for sending to different pages

I have a table in my database call Employee and one column is call IdPosition that is referred to another table call Position.

Here is my code

[HttpPost]
    public ActionResult Autorizacion(Pepitos.Models.Employee employee)
    {
        using (pepitosEntities db = new pepitosEntities())
        {
            var userDetails = db.Employees.Where(x => x.Username == employee.Username && x.Password == employee.Password).FirstOrDefault();

            if (userDetails == null)
            {
                employee.ErrorLoginMensaje = "Username or Password incorrect";
                return View("Login",employee);
            }
            else
            {
                Session["IdEmployee"] = userDetails .IdEmployee;
                Session["name"] = userDetails.Name;
                return RedirectToAction("EmployeesIndex", "EmployeesHome");
            }
        }

    }

回答1:


Now what you need to do is check the role after the username and password matches and then redirect accordingly.for that i assumed you have role column in your database table along with username and password.

 using (pepitosEntities db = new pepitosEntities())
    {
        var userDetails = db.Employees.Where(x => x.Username == employee.Username && x.Password == employee.Password).FirstOrDefault();

        if (userDetails == null)
        {
            employee.ErrorLoginMensaje = "Username or Password incorrect";
            return View("Login",employee);
        }
        else
        {

            var userRole=userDetails.role; //get the role of the user i.e whether user is admin or any other role

            if(userRole=="Admin")
            {
               Session["IdEmployee"] = userDetails .IdEmployee;
               Session["name"] = userDetails.Name;
               return RedirectToAction("EmployeesIndex","EmployeesHome");
            }
            else if(userRole=="User")
            {
                Session["IdUser"] = userDetails .IdUser;
                Session["name"] = userDetails.Name;
                return RedirectToAction("UserIndex","UserHome");
            }
            //and so on
        }
    }

hope it helps!



来源:https://stackoverflow.com/questions/50431706/mvc-custom-login-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!