【问题标题】:blazor role based columnsBlazor 基于角色的列
【发布时间】:2021-02-15 03:17:08
【问题描述】:

我有基于 Blazor 服务器的应用程序。我基本上在应用程序中为管理员显示数据库列。身份验证是使用 Azure AD 完成的,在我添加的 startup.cs 中

options.AddPolicy("AppAdmins", policy => policy.RequireRole("Admin", "SuperAdmin", "Owner"));

在我的主页中

<AuthorizeView Policy="AppAdmins">
    <Authorized>
        @Body
    </Authorized>
    <NotAuthorized>
        You are not authorized to use this application.
    </NotAuthorized>
</AuthorizeView>

这有效,现在对于特定角色用户,我需要显示特定于角色的 db 列。如何访问 Index.razor 或 Index.razor.cs 中的角色以过滤字段?

我是 Blazor 和 .Net Core 的新手。

【问题讨论】:

  • 如果有人遇到这种情况,可以查看stackoverflow.com/a/59784095/1820783。我花了 2 天时间才弄清楚它是如何完成的,我必须浏览所有论坛文章,微软文档非常庞大。

标签: .net-core authorization blazor


【解决方案1】:

您可以在组件中注入 AuthenticationStateProvider,获取 用户,检查他是否已通过身份验证,然后检索分配给他的角色。

@using System.Security.Claims
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider


 var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            var identity = (ClaimsIdentity)user.Identity;
            var roleClaims = identity.FindAll(identity.RoleClaimType);

           foreach (var existingClaim in roleClaims)
           {
             // Do something with the roles...
            }
        }
        else
        {
           // "The user is NOT authenticated.";
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2013-06-05
    • 2022-01-01
    相关资源
    最近更新 更多