.net-core - 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 的新手。
解决方案
您可以在组件中注入 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.";
}
推荐阅读
- c++ - 如何将包含括号的字符串列表展平为单个列表?
- postgresql - postgresql - 如何实现/使用视图作为表中的计算列
- java - java.io.FileNotFoundException: .\cfg\users(系统找不到指定的路径)
- react-native - 从数组反应本机填充选择器内容
- docker - ERROR: 'NoneType' object has no attribute 'replace' (HTTP 500) openstack magnum client
- sparql - sparql 查询超时。是否有另一种方法可以为我的案例查询 sparql?
- excel - Excel VBA 颜色代码 XY 散点图按三维
- python - Python / Scrapy:如何确定页面是否为html?
- mysql - 我需要一个子节点的所有父节点的列表
- arraylist - 如何根据其对象属性值从 ArrayList 获取最小值/最大值?