rotemk55
rotemk55

Reputation: 1

Force ASP .Net Web API to block HTTP requests with Error (403)

I would like to configure my project to not allow http requests with the following restrictions:

  1. It must be a global restriction for all APIs (via web.config, script in the installer, etc.)
  2. It must be hard coded(not pressing "Require SSL" on the APP in the IIS)
  3. No "redirect"- just return error (403)

my ideal option would be to configure "Require SSL" by a script which runs in the installer.

Upvotes: 0

Views: 1359

Answers (1)

Jesse Squire
Jesse Squire

Reputation: 7745

This can be accomplished by writing a simple ActionFilter that inspects the request and responds when the scheme is not set to ssl. A very minimal implementation may look something like:

public class RequireHttpsAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
        }
    }
}

To make this apply everywhere, you'll likely want to register it as a global filter in the WebAPI configuration when your application is bootstrapping. That would look something like:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new RequireHttpsAttribute());

        // ... More configuration ...
    }
}

If you search the web a bit, you can find many examples of similar filters with more robust logic that may better meet your needs.

Upvotes: 2

Related Questions