Lets assume that we are using authentication with "Abc" schema and respective handler and everything is great. We are able to secure controller simply with
[Authorize(AuthenticationSchemes = "Abc", Roles = "admin")] attribute
But now appeared need to be able to secure controller's endpoints with "Xyz" schema as well (so request should correspond to demands of both schemes).
So, I thought that registering new schema and handler are enough to be able to use [Authorize] as follows and receive AND logic:
[Authorize(AuthenticationSchemes = "Abc", Roles = "admin")]
[Authorize(AuthenticationSchemes = "Xyz")]
public class UserController : ControllerBase
{
}
But instead valid request to controller results in "Forbidden" response status (note that not even in "Unauthorized").
Also I find it interesting, that when we are applying [Authorize(AuthenticationSchemes = "Xyz")] on action method instead of controller - everything works as desired.
P.S: MvcOptions.AllowCombiningAuthorizeFilters in Startup is already set to false.
I am guessing that it still somehow merges authorization logic when both of attributes present at same (controller in this case) level.
Does anyone know what I'm missing? Probably I think in wrong direction at all and there is a appropriate way to do multi schema authentication So, please, feel free to provide your ideas.
I think this might have been answered here.
When you see complex authorization attributes like in this case, policy-based authorization can help keep things maintainable and simple.
What you would end up with using policies is something like
services.AddAuthorization(options =>
{
options.AddPolicy("MyPolicy", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole("Admin");
policy.AddAuthenticationSchemes("Abc", "Xyz");
});
});
and you'd decorate either your controller or any of its methods with nothing more than
[Authorize(Policy = "MyPolicy")]
Have a look at the official docs as well to find out how it's done and what it can offer you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With