Joshua Ohana
Joshua Ohana

Reputation: 6121

How to restrict only a subset of WebApi authorize routes?

We have an application which requires some users to be unable to access the majority of available routes, and only able to access a few. We are using standard .net [anonymous] annotations for the public calls, but need to add some additional layer in between allowing some calls and not allowing others.

Is there a way to add custom logic to the authorization function based on some annotation?

Upvotes: 0

Views: 43

Answers (1)

Eatos
Eatos

Reputation: 464

Yes, You are in need of policy based authorisation.

At the glance You need to:

  1. Add policy configuration (name and set of rules that have to be satisfy to concider a user as a member of that group defined by the policy) as a part of ConfigureServices(IServiceCollection) configuration,
  2. Define IAuthorizationRequirement for the policy. Those must be satisfied in order to clasify user as a part of the policy. Those requirements are going to be validated by IAuthorizationHandler<T> that must be regisered as a normal service. Actually this is the guy which decide if the rule is ok against a user or not, by calling either Success or Fail on the context given. We are not returning true or false here, just calling one of thise two methods to make a decision.
  3. Add proper attributes to Your either controllers and/or actions.

Using policy is a more generic approach than roles but You can also use them if You already have them defined. Policies are more like what You must have to pass" while role based autorisation in more like "who You are".

Upvotes: 2

Related Questions