【问题标题】:Nancy Fx Razor views how to show or hide elements based on user rolesNancy Fx Razor 查看如何根据用户角色显示或隐藏元素
【发布时间】:2014-12-31 05:50:08
【问题描述】:

我正在使用 Nancy 和表单身份验证。我有一个布局视图,根据用户是否经过身份验证显示登录或注销链接:

 @if (@Html.RenderContext.Context.CurrentUser.IsAuthenticated())
            {
                <p><small><span style="padding-right:15px"><em>@Html.RenderContext.Context.CurrentUser.UserName</em></span>
                    <a href="@Url.Content("~/logout")">Logout</a></small></p>
            }
            else
            {
                <p><small><a href="@Url.Content("~/login")">Login</a></small></p>
            }

在我的整个应用程序中,我将拥有只对具有正确角色的人可见的元素。 我的问题是这个。处理这个问题的最佳方法是什么?我应该在视图中检查角色,然后根据用户角色显示/隐藏元素还是在模块中显示不同的视图?

【问题讨论】:

    标签: forms authentication roles elements nancy


    【解决方案1】:

    我最终在布局中使用部分视图来根据权限提供不同的导航部分。

    @if (@Html.RenderContext.Context.CurrentUser.IsAuthenticated())
         {
            if (@Html.RenderContext.Context.CurrentUser.Claims.Contains("Admin"))
            {
                @Html.Partial("Views/Partials/_AdminMenu")
            }
            else if (@Html.RenderContext.Context.CurrentUser.Claims.Contains("Editor"))
            {
                @Html.Partial("Views/Partials/_EditorMenu")
            }
             else if (@Html.RenderContext.Context.CurrentUser.Claims.Contains("Viewer"))
            {
                @Html.Partial("Views/Partials/_ViewerMenu")
            }
             else
             {
                @Html.Partial("Views/Partials/_PublicMenu")
             }
         }
         else
         {
             @Html.Partial("Views/Partials/_PublicMenu")
         }
    

    如果存在显着差异,我将呈现来自模块的不同视图,如果到达他们不应该到达的地方,则将用户发送到“权限被拒绝”类型的视图。

    我发现这会将用户重定向到被拒绝的视图。在模块顶部添加一个后挂钩。

     public class EditUserRoleModule : NancyModule
        {
            public EditUserRoleModule()
            {
            // add an after hook to send the user to access denied if they are NOT admin
            After += context =>
            {
                if (context.Response.StatusCode == HttpStatusCode.Forbidden)
                    context.Response = this.Response.AsRedirect("/denied");
            };
    
            this.RequiresAnyClaim(new[] { "admin" });
    

    【讨论】:

      猜你喜欢
      • 2018-08-09
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多