Windows 使用数据库和 C# (MVC) 的身份验证

Windows authentication using database and C# (MVC)

我有一个数据库 table,其中列出了所有公司员工。他们为每个员工定义了角色(a、b、c)。例如员工 1 具有角色 a,员工 2 具有角色 b,依此类推。

现在,我想检查员工是否具有这 3 个角色中的任何一个。如果是,请为该用户提供网站访问权限。如果没有向该用户提及角色,则拒绝访问。 c# 代码应该能够获取 windows 登录信息,然后查询数据库。

谁能告诉我如何使用 C# 代码并开始工作

扩展 AuthorizeAttribute 的过滤器属性。它获取用户在数据库中的角色,并与分配给每个控制器或方法的角色进行比较。

public class UserRoleAuthorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //Data Repository. Getting data from database
        var repository = new LoginRoleRepository();
        //GetCharacterSeparator is an Extension method of String class
        //It seperates the comma separated roles.
        //The data comes from the controller
        var roles = Roles.GetCharacterSeparator(',', true);

        if (httpContext.User.Identity.IsAuthenticated)
        {
            //Here I check if the user is in the role, you can have your own logic. The data is gotten from DB.
            var userRoles =
                repository.All().Where(obj => obj.Login.Username == httpContext.User.Identity.Name).Single().Roles;


            foreach (var role in roles)
                if (userRoles.Any(obj => obj.Name == role))
                    return true;
        }
        return false;
    }
}

然后您只需如下定义每个方法或控制器的属性。

//Both Doctors and Receptionist have access to Patient controller.
[UserRoleAuthorize(Roles="Doctors, Receptionist")]
public class PatientController : Controller
{
     //Both Doctors and Receptionist have access to Schedule an appointment for patients.
     public ActionResult Schedule()
     {
            return View();
     }

     //Only Doctors have access to Treat patients.
     [UserRoleAuthorize(Roles="Doctors")]
     public ActionResult TreatPatient()
     {
            return View();
     }
}

您需要添加额外的信息:

//Here seperate the roles as Doctor:ReadWrite, Receptionist:Read
//If you see Doctor:ReadWrite means the doctor has Read and Write and so on.
//This code is in AuthorizeCore
var roles = Roles.GetCharacterSeparator(',', true);

//And Add the bellow to the controllers and methods.
[UserRoleAuthorize(Roles="Doctors:Write, Employees:Read")]