0

I want to develop dynamic roles authorization using .net core webAPI, my structure is that user have one role and the role have some function or features to access

my question is there is any way yo get the function name where authorization policies applied

as example I have the following code

   [Authorize(Roles = "Admin", Policy = "isHasPermission")]
   public async Task<IActionResult> GetAllAsync()
    {
        var users = await _userService.GetAllAsync();
        var userDtos = _mapper.Map<IList<UserDto>>(users);
        return Ok(DataMessage.Data(new { users = userDtos }));
        //return Ok(userDtos);
    }

and my policy is something like that

protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        isHasPermissionRequirement requirement)
    {

      /*
       CAN I GET THE FUNCTION NAME "GetAllAsync" HERE!
       TO VALIDATE IF IT IS ONE OF USER'S FEATURE
      */

        return await Task.CompletedTask;
    }

So that I need to get the function name in the policy to validate user's permissions, if it is possible or not?

1 Answers1

0

You are doing it backwards: The way policies work is that you say that a certain action has requirements. It is not a valid requirement to then circle back to where the policy is used. Policies should be completely separate from what you are trying to access. If a certain thing specifies a policy, then just the presense of the policy should be all that’s necessary.

If you want to have your logic actually check what you are trying to access, then you could look into authorization filters instead. When they are called, they pass an AuthorizationFilterContext which also contains information about the route and action the user is trying to access. With that, you can get the action name for example using (context.ActionDescriptor as ControllerActionDescriptor).ActionName.

poke
  • 369,085
  • 72
  • 557
  • 602