2017-04-09 48 views
0

(查看)在视图或控制器中进行授权会更好吗?

//deny access to these Roles Beside Admin(Role3) 
if (RoleId == 1 || RoleId == 2 || RoleId == 4) 
{ 
//Redirect to home if RoldId is not 3 
    Response.Redirect("~/Home/Index"); 
} 

(控制器)

//deny other Roles Beside Admin 
[Authorize(Roles = "Admin")] 
public ActionResult AdminOnly() 
{ 
return View(); 
} 

工作都相同的,但哪个更好,为什么?

+4

第二种方法是标准方法。 –

+5

假设您将来会获得新角色。然后,这个角色将与方法1自动获得管理员访问权限。在这种情况下,白名单总是比黑名单更好,因此做的方法2. – LSA

+0

你从哪里获得'role id'? – oldbam

回答

0

由于您的观点得到了Razor视图引擎在服务器端渲染到HTML代码,您可能会注意到没有区别。具体而言,两种方法的主要区别在于,如果第一种方法在发生错误或抛出异常的情况下不安全,这会导致丑陋的错误页面和低效的异常处理。

这是而后一种方法可以看作是最好的,因为它可以让你处理所有异常或错误的控制器,或者更重要的是,你可以根据用户的角色使你返回的视图。

例如:

[CustomAuthorize] 
public IActionResult AdminDashboard(){ 
    if(HttpContext.User.IsInRole("Admin")) 
     return View("X"); 
    else if (HttpContext.User.IsInRole("Guest")) 
     return View("Y"); 
    else 
     return RedirectToAction("Some Action"); 
     // Or throw an exception 
} 

,此外,你可以写一个异常处理属性来处理渲染后的结果,当在控制器级别或抛出异常。这可以通过继承Attribute并实现IActionFilterIResultFilter接口来完成。

例如:

public class HandleLoginAttribute : Attribute, IActionFilter, IResultFilter 
{ 
    public void OnActionExecuted(ActionExecutedContext context) 
    { 
     if (context.Exception != null) { 
      // Handle exceptions thrown by the action api 
     } 
    } 

    public void OnActionExecuting(ActionExecutingContext context) 
    { 

    } 

    public void OnResultExecuted(ResultExecutedContext context) 
    { 
     if (context.Exception != null) 
     { 
      // Handle exceptions thrown when rendering the view 
     } 
    } 

    public void OnResultExecuting(ResultExecutingContext context) 
    { 

    } 
}  

所以,你可以有这样的:

[HandleLogin] 
[CustomAuthorize] 
public IActionResult AdminDashboard(){ 
    if(HttpContext.User.IsInRole("Admin")) 
     return View("X"); 
    else if (HttpContext.User.IsInRole("Guest")) 
     return View("Y"); 
    else 
     return RedirectToAction("Some Action"); 
} 

而且主要优点是可以有效地重用所有这些,而你不能做(或者你不能有效地做)里面的意见。

0

如果一个基于角色的一个控制器。 虽然视图仍然可以使用一些约定,如果有进一步的粒状分布需求。

例如。接待员和医生都可以访问相同的患者详细信息,但使用基于视图的授权后,您可能会精细地分发哪些字段可用于查看或编辑的角色。

相关问题