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

编程入门 行业动态 更新时间:2024-10-24 04:48:51
本文介绍了检查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属性的多个策略之一

本文发布于:2023-11-10 09:36:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575019.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   属性   策略   NET   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!