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.
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.