首页 > 解决方案 > Blazor 基于角色的列

问题描述

我有基于 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>

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

我是 Blazor 和 .Net Core 的新手。

标签: .net-coreauthorizationblazor

解决方案


您可以在组件中注入 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.";
        }

推荐阅读