How to pass custom argument to authorization polic

2020-05-06 13:46发布

问题:

I need a custom attribute for my rest API in asp.net core MVC. I want to add this attribute optionally to some of my APIs. This attribute checks if the API is accessible to user or not based on some condition and throws a 403 if it's not accessible. I was using filters to achieve this and the issue with filter is that filter code gets executed whether the attribute is added or not to my API. I would want that my filter code is executed only when this attribute is added to the API.
My colleague suggested that I should be using authorization policy instead of filters for this use case. Policies are executed only when it's added to the API. Also since I am throwing 403, authorization policy is a better candidate. I explored authorization policy but my issue is I am unable to pass custom attributes to Authorization policy.

For example, I was able to do this using filters and custom attributes.

[MyCustomFeature("param1", "param2")]

How can I do the same in authorization policy? I am using this example for authorization policy. Custom Authorization attribute asp.net core

回答1:

See here. Strongly recommend reading top to bottom.

The summary is that, regardless of how you tap in to the policy-basd auth system, a policy is always resolved via a single string. So, to get what you want, you need to:

  • Implement a custom attribute that subclasses AuthorizeAttribute and that takes the arguments you pass in and uses them to generate a policy name string. Read the "Custom Authorization attributes" example in the linked docs page closely, see how it actually stores the value of "Age" in the Policy string.
  • Implement and register a custom IAuthorizationPolicyProvider that can interpret the strings generated by your custom attribute and generate the appropriate policy on the fly.

There's not a ton of code involved and it's not super complex, but it's a little strange/awkward that it comes down to putting stuff into a string.