Yosep Kim
Yosep Kim

Reputation: 2941

Custom authentication filter (implementing IAuthenticationFilter) is not firing

I have an ASP MVC 5 application, and I am having trouble getting a custom authentication filter to work.

I have created a custom authentication filter in a folder "CustomFilters" as shown below:

public class CustomBasicAuthAttribute : ActionFilterAttribute, IAuthenticationFilter
{

    public void OnAuthentication(AuthenticationContext context)
    {
        // does not fire... :(
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext context)
    {
        // does not fire... :(
    }
}

And in my ProductController I decorated one of the methods as in:

public class ProductsController : ApiController
{

    [CustomBasicAuth]
    [HttpGet]
    [Route("clients/{id}/products")]
    public IEnumerable<Products> GetByClientId(int id)
    {

        return new List<Products>();
    }

For some reason, though, the OnAuthentication method in the CustomBasicAuth class never fires. I tried to decorate the whole controller, and also tried to load it globally, but none of it worked.

I read and followed a lot of online articles regarding this, and it looks like this should just work.

Any help would be greatly appreciated.

Upvotes: 1

Views: 2666

Answers (2)

Aaron
Aaron

Reputation: 1832

This also happened to me, but in my case I had decorated the controller methods I wanted to protect with ONLY my custom basic authentication attribute, but completely forgot to also decorate with the normal MVC "Authorize" attribute. You need to still have the "Authorize" attribute there so that MVC protects the method or class and then fires your custom attribute filter..

Upvotes: 0

Alain Bates
Alain Bates

Reputation: 466

The issue here is that you're implementing the wrong sort of IAuthenticationFilter for your controller type. Your controller class inherits from ApiController, so this appears to be a Web API project. To implement custom authentication for Web API, your CustomBasicAuthAttribute needs to implement the System.Web.Http.Filters.IAuthenticationFilter interface. The methods on that are AuthenticateAsync and ChallengeAsync.

The CustomBasicAuthAttribute implementation shown clearly inherits from System.Web.Mvc.Filters.IAuthenticationFilter, as it's using OnAuthentication and OnAuthenticationChallenge. That attribute would fire correctly when placed on an action in a standard MVC controller, just not ones inheriting from APIController.

Upvotes: 5

Related Questions