Reputation: 2218
I have an ASP.net Core application with an API section. I want to Require Https for all access to the API.
However Asp.net docs states
Warning
Do not use RequireHttpsAttribute on Web APIs that receive sensitive information. RequireHttpsAttribute uses HTTP status codes to redirect browsers from HTTP to HTTPS. API clients may not understand or obey redirects from HTTP to HTTPS. Such clients may send information over HTTP. Web APIs should either:
- Not listen on HTTP.
- Close the connection with status code 400 (BadRequest) and not serve the request.
Question
Is there a way to reject but not redirect incoming https on a controller/method level?
Upvotes: 2
Views: 750
Reputation: 2926
Since you are using asp.net core, let's write an ActionFilterAttribute
that we are going to apply to any controllers or actions that we want return a Forbidden result instead of a Redirect if the request scheme is HTTP and not HTTPS
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class RestrictHttpsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.HttpContext.Request.IsHttps)
{
context.Result = new ForbidResult();
}
else
{
base.OnActionExecuting(context);
}
}
}
How To Use
This is how to use the action filter on a controller:
[RestrictHttps]
public class ExampleController : Controller
{
// controller code goes here.
}
For further reading, checkout Filters in ASP.NET Core
Upvotes: 4