Search code examples
c#asp.net-mvc-4asp.net-web-apiaction-filterauthorize-attribute

Execute filter whenever AuthorizeAttribute is used on a Controller/Method


So we've got a bunch of API Controllers using the [Authorize] attribute, and I want to be able to execute a filter (to log stuff) wherever that attribute is used.

We have this Ninject with the bellow snippet of code, but we're trying to move away from Ninject (to Autofac)

kernel.BindHttpFilter<AuthLogFilter>(FilterScope.Action)
     .WhenActionMethodHas<AuthorizeAttribute>()
     .InSingletonScope();

A stripped out version of AuthLogFilter looks something like:

 public class AuthLogFilter : IActionFilter
    {
        private readonly ILog _log;

        public AuthLogFilter(ILog log)
        {
            _log = log;
        }

        public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            ClaimsPrincipal principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
            _log.Info("log some stuff about the principal");
        }
    }

How do I do this either using native filters? Or with Autofac.


Solution

  • The only solution I could find was to programmatically check for the filter in the OnActionExecuting for the filter, as described in the following -

    https://stackoverflow.com/a/6117456/211718