2017-09-15 93 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>