I've an app that will have multiples level of organization, and for each level, there will be rights(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
.
Therefore, I cannot just do the usual 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. `
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?)?
You can use HttpContext
to look at the claims in the JWT.
I have recently been working with authorizations in .NET API and this is what I done:
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.
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. Else, you'd probably have to use it via DI, but should all work the same.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.