2017-09-15 92 views
1

在ASP.NET Core MVC中我想隱藏用戶無權訪問的導航欄中的鏈接。目前我在以前的項目中使用的MvcSiteMapProvider不支持ASP.NET Core MVC。ASP.NET Core MVC導航安全修剪

幾年前,一個類似的question被問到,雖然建議的答案會起作用,但它需要在控制器/操作上重複授權過濾器集以確保隱藏鏈接。

這是怎麼做到的,並且在ASP.NET Core MVC中是否有任何當前的安全調整示例?

回答

0

我已經創建了自定義標籤助手來處理這個問題。

[HtmlTargetElement(Attributes = "asp-roles")] 
public class SecurityTrimmingTagHelper : TagHelper 
{ 
    [ViewContext] 
    public ViewContext Context { get; set; } 

    [HtmlAttributeName("asp-roles")] 
    public string Roles { get; set; } 

    /// <summary> 
    /// Hides html element if user is not in provided role. 
    /// If no role is supplied the html element will be render. 
    /// </summary> 
    /// <param name="context"></param> 
    /// <param name="output"></param> 
    public override void Process(TagHelperContext context, TagHelperOutput output) 
    {    
     if (!Context.HttpContext.User.Identity.IsAuthenticated) 
     { 
      output.SuppressOutput(); 
     } 

     if (!string.IsNullOrEmpty(Roles)) 
     { 
      var roles = Roles.Split(','); 
      foreach (var role in roles) 
      { 
       if (!Context.HttpContext.User.IsInRole(role)) 
       { 
        output.SuppressOutput(); 
        return; 
       } 
      } 
     } 
    } 
} 

您可以將其應用於任何html元素。如果你想將它僅適用於特定HTML元素(可以說<li>)然後改變HtmlTargetElement

[HtmlTargetElement("li",Attributes = "asp-roles")] 

然後在視圖中,你可以做

<li asp-roles="Admin"><a href="/Profile/Admin">Admin</a></li>