Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom IAuthenticationFilter and AllowAnonymous in Web API

I would like to make use of AllowAnonymous and a custom AuthenticationFilter. Can someone point me in the right direction to make use of AllowAnonymous or another alternative? Thanks

I've created my own custom filter that inherits from System.Attribute and implements System.Web.Http.Filters.IAuthenticationFilter

 public class MyCustomAuthenticationAttribute : Attribute, IAuthenticationFilter

I have been able to successfully add the logic for the AuthenticateAsync method

 public async Task AuthenticateAsync(
     HttpAuthenticationContext context, 
     CancellationToken cancellationToken) {}

My problem is that I need to ignore some of my Web API controller actions or controllers. I thought that I could use System.Web.Http.AllowAnonymousAttribute to do this. For example here is a really simple example showing intent.

[MyCustomAuthentication]
public class HomeController : ApiController
{
    // no authentication needed allow anonymous 
    [HttpGet]
    [Route("hianonymous")]
    [AllowAnonymous]
    public IHttpActionResult Hello(string name) {
        return Ok(new { message = "hello " + name }); 
    }

    // needs to be authenticated 
    [HttpGet] 
    [Route("hiauthenticated")]
    public IHttpActionResult Hello() {
        var name = User.Identity.Name;
        return Ok(new { message = "hello authenticated user " + name });  
    }
}

The problem is that Authenticate() is still called on MyCustomAuthenticationAttribute. I would like to use AllowAnonymous or some other method to accomplish this. Thanks for any input.

I know that I can use my custom authentication attribute at the action level and not controller level but there are cases I would like an entire controller or even as a global filter so I need to be able to excluded on an individual action or controller basis.

like image 290
Scott Avatar asked Dec 17 '14 17:12

Scott


1 Answers

Your implementation of IAuthenticationFilter should do NOTHING if it does not find an Authorization scheme it does not recognize.

http://www.asp.net/web-api/overview/security/authentication-filters

// 2. If there are no credentials, do nothing.
if (authorization == null)
{
    return;
}

// 3. If there are credentials but the filter does not recognize the 
//    authentication scheme, do nothing.
if (authorization.Scheme != "Basic")
{
    return;
}

The idea is that your filter is simply a way to AUTHENTICATE using a known scheme.

You will still need to use the built in AuthorizeAttribute and AllowAnonymousAttribute to control AUTHORIZATION.

like image 67
hatcyl Avatar answered Nov 13 '22 19:11

hatcyl