MVC自定义登录身份验证 [英] MVC custom login authentication

查看:86
本文介绍了MVC自定义登录身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在MVC中开发应用程序,登录时遇到问题,我想知道如何根据用户角色来管理登录.

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

我的数据库调用Employee中有一个表,一个列称为IdPosition,它引用了另一个表调用Position.

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

这是我的代码

[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");
            }
        }

    }

推荐答案

现在,您需要做的是在用户名和密码匹配后检查角色,然后进行相应的重定向.为此,我假设您在数据库表中有角色列以及用户名和密码.

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
        }
    }

希望有帮助!

这篇关于MVC自定义登录身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆