Lane Goolsby
Lane Goolsby

Reputation: 681

Excluding specific methods from Autofac AsWebApiAuthenticationFilterFor

I am trying to add authentication for all methods in a WebApi2 controller except for one health endpoint named Ping that exists on all controllers. I have the auth working properly, but I don't see a way to apply the exclusion.

I would like to do something like the Exclude() below:

      builder.Register(e => new MyCustomAuthFilter(
      e.Resolve<IInjectedService>(),
      e.Resolve<IAnotherService>()))
      .AsWebApiAuthenticationFilterFor<MyController>()
      .Exclude(Ping)
      .InstancePerRequest();
      builder.RegisterWebApiFilterProvider(config);

Upvotes: 0

Views: 185

Answers (1)

Travis Illig
Travis Illig

Reputation: 23934

Unfortunately there's no opt-out on a per-item basis at this moment. You basically have the ability to attach to the whole controller or to an individual action, but that's it.

There's a long running issue where folks would like the ability to attach a single filter registration to multiple controllers. I raise that because it also means you can't just do this:

// Doesn't work, this isn't a thing
builder.RegisterType<Filter>()
       .AsWebApiAuthenticationFilterFor<Controller>(c => c.Get())
       .AsWebApiAuthenticationFilterFor<Controller>(c => c.Post());

That is, as it stands today you couldn't foreach over the methods you want to opt-in and just have that work.

There's also a long-running issue to allow filters to be attached by predicate. If that was implemented, you could do something like this:

// Doesn't work, this isn't a thing
builder.RegisterType<Filter>()
       .AsWebApiAuthenticationFilterFor<Controller>(method => method.Name != "Delete");

Unfortunately, there's a ton of work to do, so without some help from the community in the form of PRs or some additional project owners you may not see these any time soon.

The best option I could offer you without that is to separate your controller into two different classes - the methods you want covered in one controller, the methods you don't in a different controller. Derive the two from a common base class to share logic.

Upvotes: 1

Related Questions