如何 set/find 来自 .NET Core 中基于组织的身份的用户角色

How to set/find user roles from Organization based Identity in .NET core

我正在尝试找出用户在 Blazor Server 应用程序中拥有什么角色,该应用程序为使用 MS 帐户和 Azure Active Directory 的组织设置了身份验证。我想这些角色是由管理 MS 帐户的 IT 运营团队设置的,但我找不到在哪里可以验证这一点。

所以我想知道:使用 Org 身份验证时,角色设置在哪里如何更改它们并且是否有一种简单的方法来查看经过身份验证的用户具有哪些角色

我尝试使用下面的级联参数在 MS doc 示例代码中寻找经过身份验证的用户的角色:

@page "/"

<button @onclick="LogUsername">Log username</button>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        LogUsername();
    }

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            var test = user.Claims.Where(c => c.Type.Contains("Role")); // also tried "role"
            string role = test.FirstOrDefault().ToString();
            Console.WriteLine($"{role} is authenticated.");
        }
        else
        {
            Console.WriteLine("The user is NOT authenticated.");
        }
    }
}

Identity 有一个 RoleClaimType,但我找不到任何其他信息可以说明给定用户的 Role 是什么。我是不是找错地方了?我找不到任何关于 Organiztion Authentication 如何与 .NET core 和 Blazor 中的 Identity 一起工作的详细文档,所以任何正确方向的提示、建议或推动都将不胜感激!

角色在 Azure 门户中设置。 Azure Active Directory -> 应用注册 -> [你的应用] -> 角色和管理员。对于自定义角色,您的组织将需要 Azure AD Premium P1 或 P2 许可证。

至于如何取回它们,这里引用 documentation:

Get role claims. When a user signs in, the application receives the user's assigned role(s) in a claim with type http://schemas.microsoft.com/ws/2008/06/identity/claims/role (the roles claim in a JWT token).

A user can be assigned multiple roles, or no role. In your authorization code, don't assume the user has exactly one role claim. Instead, write code that checks whether a particular claim value is present:

if (context.User.HasClaim(ClaimTypes.Role, "Admin")) { ... }

对于那些看起来像我的人,在 .Net 6 中

关于如何在 Blazor 中启用角色的官方文档docs.microsoft.com

关闭组件以供查看

<AuthorizeView Roles="Admin">  
    <div> ..... </div>
</AuthorizeView>

获取用户第一个角色的名称

<AuthorizeView>
    <Authorized>
       <p>@context.User.Claims.FirstOrDefault(c=>c.Type == "role").Value</p>
    </Authorized>
</AuthorizeView>

从视图中关闭页面

@attribute [Authorize(Roles = "Admin, Normal")]