Xzil0
Xzil0

Reputation: 173

Role-based and policy based authentication on same controller action

From MS docs i can see that I can define multiple roles. [Authorize(Roles = "HRManager,Finance")] Which means that user has to be in HRManager OR Finance role.

I also have resource based policy defined for this action, named "ResPolicy1".

I want to accomplish that user can be in role HRManager OR in role Finance OR ResPolicy1 is satisfied, any of the three.

  1. Can I use AuthorizeAttribute like this [Authorize(Roles="HRManager,Finance", Policy="ResPolicy1"]?
  2. Is it possible to have both policy and role based authorization on the same controller action?

Upvotes: 1

Views: 696

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 27987

Can I use AuthorizeAttribute like this [Authorize(Roles="HRManager,Finance", Policy="ResPolicy1"]? Is it possible to have both policy and role based authorization on the same controller action?

We could have both policy and role based authorization on the same controller action. Like below:

   [Authorize(Policy = "UserResource", Roles = "Users")]
    public IActionResult Index()
    {
        return View();
    }

If we add Policy and Roles for the same controller, that means the user should match both role Authorize and policy Authorize.

If the user is just in role but not pass the policy authorize, he will receive the 403 forbidden.

If the user is just pass the policy authorize but not in role, he will also receive the 403 forbidden.

If you want to accomplish that user can be in role HRManager OR in role Finance OR ResPolicy1 is satisfied, any of the three, you could write your own logic in the custom Authorization handlers. More details about how to achieve it, you could refer to this article.

Upvotes: 2

Related Questions