[英]How to check if a user is in a role in Asp.Net Core Identity Framework
I've an app that will have multiples level of organization, and for each level, there will be rights(admin-reader-...).我有一个应用程序,它将具有多个级别的组织,并且对于每个级别,都会有权限(admin-reader-...)。
I want to create(and maintain) a list of roles for each user, but it means that a lot of those roles name will be dynamic, like {id-of-the-organization]-admin
.我想为每个用户创建(和维护)一个角色列表,但这意味着很多角色名称都是动态的,比如{id-of-the-organization]-admin
。
Therefore, I cannot just do the usual Authorize
:因此,我不能只做通常的Authorize
:
[Authorize(Roles = "Administrator, PowerUser")]
public class ControlAllPanelController : Controller
{
public IActionResult SetTime() =>
Content("Administrator || PowerUser");
[Authorize(Roles = "Administrator")]
public IActionResult ShutDown() =>
Content("Administrator only");
}
I would like to have something like我想要类似的东西
public class ControlAllPanelController : Controller
{
[Authorize]
public IActionResult SetTime(Guid organizationId) {
someService.Authorize(organizationId+"-SetTime");//Throw exception or return boolean
//... rest of my logic
}
}
Not sure how to achieve this?不确定如何实现这一目标? I've seen example of this with the IAuthorize
service, but this was requiring to provide policies name, which I don't have for this case(Or maybe there is one by default but I don't know its name. `我已经在IAuthorize
服务中看到过这样的例子,但这需要提供策略名称,对于这种情况我没有(或者默认情况下可能有一个,但我不知道它的名称。`
I've seen that the ClaimsPrincipal
has a IsInRole
, but I'm not totally sure it get the latest information from Asp.Net Core Identity Framwork(from the user manager) (only what is stored inside the token?)?我已经看到ClaimsPrincipal
有一个IsInRole
,但我不完全确定它从 Asp.Net Core Identity Framwork(来自用户管理器)获取最新信息(仅存储在令牌中的内容?)?
You can use HttpContext
to look at the claims in the JWT.可以使用HttpContext
查看JWT中的声明。
I have recently been working with authorizations in .NET API and this is what I done:我最近一直在使用 .NET API 中的授权,这就是我所做的:
var identity = this.HttpContext.User.Identities.FirstOrDefault();
var role = identity.Claims.FirstOrDefault(x => x.Type == "role").Value;
if (role != "Admin")
{
return Unauthorized("You don't have to correct permissons to do this.");
}
So I'm getting the Identity details, then searching the claims for the role
claim.所以我正在获取身份详细信息,然后在声明中搜索role
声明。
As a side note, Im using this in a controller inheriting from ControllerBase
so I believe HttpContext
is a property of this class so no need to inject it if you're using this.作为旁注,我在继承自ControllerBase
的 controller 中使用它,因此我相信HttpContext
是此 class 的属性,因此如果您正在使用它,则无需注入它。 Else, you'd probably have to use it via DI, but should all work the same.否则,您可能必须通过 DI 使用它,但都应该一样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.