Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC 中的自定义安全方案

2024年02月23日15unruledboy

我没有太多这方面的经验,我真的希望能从你们那里得到好的建议。我需要实现以下安全方案,并且我想知道实现它的最佳方法。

假设我们有员工、主管和部门经理。 Employees 和 Supervisor 都根据 off 分配了 ManagerId,并指向他们所属的部门经理。

当主管用户登录时,我希望他只能看到与他属于同一 ManagerId 的员工的记录。 如果另一个具有另一个 ManagerId 用户的主管登录并在 url 中手动输入其他员工的信息(例如:wwww.domain.com/employee/details/{id} ), 因为他的 ManagerId != 员工的 ManagerId 我希望限制访问权限。

有意义吗?

我开始对所有 ActionMethods 输入检查,例如:

public ActionResult Details(int id) 
{ 
    var employee = employeeRepository.Get(id) 
    var user = (CustomIdentity)ControllerContext.HttpContext.User.Identity; 
 
    if(employee.managerId == user.managerId) 
    { 
        Do whatever... 
    }    
    else     
    { 
        Not allowed 
    } 
} 

但是在所有 ActionMethods 中输入这些内容似乎是多余的,只是......嗯......我知道一定有更好的方法。

请您参考如下方法:

这是一个解决方案。它需要一些清理,但应该会为您提供所需的一切。

创建一个自定义的 ActionFilter,然后用它装饰您的方法。

[ManagerIdAuthentication] 
public ActionResult Details(int id) 
{ 
     // Gets executed if the filter allows it to go through. 
} 

下一个类可以在单独的库中创建,因此您可以将其包含在需要此验证的所有操作中。

public class ManagerIdAuthentication : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
        // the next line needs improvement, only works on an httpGet since retrieves 
        // the id from the url.  Improve this line to obtain the id regardless of  
        // the  method (GET, POST, etc.) 
        var id = filterContext.HttpContext.Request.QueryString["id"]; 
 
        var employee = employeeRepository.Get(id); 
        var user = filterContext.HttpContext.User.Identity; 
        if (employee.managerId  == user.managerId) 
        { 
            var res = filterContext.HttpContext.Response; 
            res.StatusCode = 402; 
            res.End(); 
            filterContext.Result = new EmptyResult();  //may use content result if want to provide additional info in the error message. 
        } 
        else 
        { 
            // OK, let it through. 
        } 
    } 
}