I'm having trouble figuring out how to implement an authorization filter in Web API using IAuthorizationFilter from System.Web.Http.Filters.
This is a simple filter I wrote to respond to all non-https requests with a 403 forbidden response:
public class HttpsFilter : IAuthorizationFilter { public bool AllowMultiple { get { return false; } } public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync( HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation ) { var request = actionContext.Request; if ( request.RequestUri.Scheme != Uri.UriSchemeHttps ) { HttpResponseMessage response = request.CreateResponse( HttpStatusCode.Forbidden ); response.Content = new StringContent( "<h1>HTTPS Required</h1>", Encoding.UTF8, "text/html" ); actionContext.Response = response; return new Task<HttpResponseMessage>( delegate() { return response; } ); } else return continuation(); } }
What I have written so far runs, but when I try to access the api over regular http, it just hangs and I never get a response.
Setting an Authentication Filter[IdentityBasicAuthentication] // Enable Basic authentication for this controller. [Authorize] // Require authenticated requests. public class HomeController : ApiController { public IHttpActionResult Get() { . . . } public IHttpActionResult Post() { . . . } }
Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.
Short answer: MVC and Web API filters are not cross compatible, and if you want to register them globally, you must use the appropriate configuration classes for each. Long answer: ASP.NET MVC and Web API are purposely designed to work in a similar way, but they are in fact different creatures.
For you scenario, you could simply derive from the "System.Web.Http.AuthorizeAttribute".
Example:
public class HttpsFilterAttribute : System.Web.Http.AuthorizeAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { //do something } }
You either need to save the task into a variable and call the task.Start()
method before returning it, or use the Task<HttpResponseMessage>.Factory.StartNew(Action action)
method to create the task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With