2

在 ASP.NET Core MVC 中,我想在导航栏中隐藏用户无权访问的链接。目前我在之前的项目中使用的MvcSiteMapProvider不支持 ASP.NET Core MVC。

几年前提出了一个类似的问题,虽然建议的答案会起作用,但它需要重复在控制器/操作上设置的授权过滤器以确保隐藏链接。

如何做到这一点,在 ASP.NET Core MVC 中是否有任何当前的安全修整示例?

4

1 回答 1

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>
于 2018-02-13T20:45:56.137 回答