检查ASP.NET Core Identity中具有Authorize属性的多个策略之一 [英] Checking for one of multiple policies with Authorize attribute in ASP.NET Core Identity

查看:433
本文介绍了检查ASP.NET Core Identity中具有Authorize属性的多个策略之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在ASP.NET Core应用程序中建立了标准的身份验证系统.

I have setup a standard authentication system up in an ASP.NET Core application.

用户,角色,角色声明(充当权限)

Users, Roles, RoleClaims(acting as permissions)

在Startup.cs中,我为每个角色和每个权限创建一个策略.假设这将使我在视图"中具有充分的灵活性,可以说我希望此按钮显示用户是属于拥有DeleteCustomer的角色的一部分,还是用户属于角色Superuser.

In Startup.cs I create a policy for each Role and each Permission. Assuming this would give me full flexibility in my Views to be able to say I want this button to show if user is part of a role that has claim DeleteCustomer or if User belongs to role Superuser.

如何使用Authorize属性执行或"条件.例如,在我的整个网站上,我都希望SuperuserRole策略对所有内容都具有完全权限.

How can I do an OR condition using the Authorize attribute. For example all throughout my site I want SuperuserRole Policy to have full permission to everything.

在一种操作方法上,我有以下内容:

Over an action method let's say I have the following:

[Authorize(Policy ="EditCustomer")]

[Authorize(Policy = "EditCustomer")]

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

This will require that the logged in user is assigned to a role that has the claim: Edit.Customer since I am creating a policy for the claim Edit.Customer. This is all working fine, but how do I say I would like any User with the Role Superuser to be able to access EditCustomer action method. Superuser is in the database as a Role and additionally added as a policy called RequireSuperUser.

推荐答案

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

You can add OR condition in Startup.cs:

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"部门的任何人也可以访问同一屏幕.以下内容对我有用,我在其中声明了部门"和用户名"的类型:

I was facing similar issue where I wanted only "John Doe", "Jane Doe" users to view "Ending Contracts" screen OR anyone only from "MIS" department also to be able to access the same screen. The below worked for me, where I have claim types "department" and "UserName":

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)))));
});

这篇关于检查ASP.NET Core Identity中具有Authorize属性的多个策略之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆