c# - 在 ASP.NET Core Identity 中检查具有 Authorize 属性的多个策略之一

标签 c# asp.net-core asp.net-core-mvc asp.net-identity asp.net-identity-3

我在 ASP.NET Core 应用程序中设置了标准身份验证系统。

Users, Roles, RoleClaims(充当权限)

在 Startup.cs 中,我为每个角色和每个权限创建了一个策略。假设这会给我的 View 提供完全的灵 active ,以便能够说我希望此按钮显示用户是否属于已声明 DeleteCustomer 的角色,或者用户是否属于角色 super 用户。

如何使用 Authorize 属性执行 OR 条件。例如,在我的整个网站中,我希望 SuperuserRole Policy 对所有内容都具有完全权限。

假设我有以下操作方法:

[授权(政策=“EditCustomer”)]

这将要求将登录用户分配给具有声明的角色:Edit.Customer,因为我正在为声明 Edit.Customer 创建策略。这一切都很好,但我怎么说我希望任何具有 super 用户角色的用户都能够访问 EditCustomer 操作方法。 super 用户作为角色在数据库中,并作为名为 RequireSuperUser 的策略添加。

最佳答案

您可以在 Startup.cs 中添加 OR 条件:

services.AddAuthorization(options => {
    options.AddPolicy("EditCustomer", policy =>
        policy.RequireAssertion(context => 
        context.User.HasClaim(c => (c.Type == "DeleteCustomer" || c.Type == "Superuser"))));
});

我遇到了类似的问题,我只希望“John Doe”、“Jane Doe”用户查看“Ending Contracts”屏幕,或者只有“MIS”部门的任何人也能够访问同一屏幕。以下对我有用,我声明类型为“部门”和“用户名”:

services.AddAuthorization(options => {
    options.AddPolicy("EndingContracts", policy =>
        policy.RequireAssertion(context => context.User.HasClaim(c => (c.Type == "department" && c.Value == "MIS" ||
        c.Type == "UserName" && "John Doe, Jane Doe".Contains(c.Value)))));
});

关于c# - 在 ASP.NET Core Identity 中检查具有 Authorize 属性的多个策略之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47209470/

相关文章:

c# - 将 key 发送到非事件应用程序

c# - 使用 IT Hit WebDAV Server 在 MS Office 中以只读方式打开 WebDAV 文档

c# - 为 HTTPS 配置 ASP.NET Core 2.0 Kestrel

c - Postman 从 api 获取数据,但 .net core 2.2 应用程序不获取数据

c# - 如何为验证属性提供本地化验证消息

c# - 页面方法多次回调

c# - ASP .NET 无法解析类型的服务

c# - Swagger - 如何在 C# 中为子对象添加定义

asp.net-core - MVC 6 安装为 Windows 服务 (ASP.NET Core 1.0.0)

javascript - 从表 th 中删除类