简体   繁体   中英

how to require HTTPS but not redirect

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM