User IAuthenticationFilter and AllowAnonymous in the web API

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

I created my own custom filter, which inherits from System.Attribute and implements System.Web.Http.Filters.IAuthenticationFilter

  public class MyCustomAuthenticationAttribute : Attribute, IAuthenticationFilter 

I was able to successfully add logic for the AuthenticateAsync method

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

My problem is that I need to ignore some actions or web API controller controllers. I thought I could use System.Web.Http.AllowAnonymousAttribute for this. For example, here is a very simple example showing intention.

 [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 being called on MyCustomAuthenticationAttribute . I would like to use AllowAnonymous or some other method for this. Thanks for any input.

I know that I can use my own authentication attribute at the action level, and not at the controller level, but there are cases when I need the entire controller or even as a global filter, so I should be able to exclude a separate action or controller.

+6
source share
1 answer

Your implementation of IAuthenticationFilter should do NOTHING if it does not find an authorization scheme that 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 just an AUTHORIZATION method using a well-known scheme.

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

+9
source

Source: https://habr.com/ru/post/979796/


All Articles