1

We have distributed web application that our customers host on premise and we want to remove the options of starting it without https. We only allow configuration using the "kestrel" section in appsettings.json and we basically want the app to throw an error on startup and then shut down if there's no valid https-endpoint in the configuration.

We already have UseHttpsRedirection() which gives a warning but doesn't force the app to terminate.

1 Answers1

0

You can create a custom middleware that fails on startup on HTTP:

public class RequireHttpsMiddleware
{
    private readonly RequestDelegate _next;

    public RequireHttpsMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.IsHttps)
        {
            throw new Exception("Not allowed to run application on HTTP.");
        }

        await _next(context);
    }
}
Moien Tajik
  • 2,115
  • 2
  • 17
  • 39
  • Wouldn't this require a request to come in before it throws the exception? – Johan Stenberg Apr 01 '19 at 08:26
  • @JohanStenberg This will actually run when the first request comes into the application pipeline. – Moien Tajik Apr 01 '19 at 09:20
  • But that means that we still have to wait for the first request to come into the server or does the server itself send a request through the pipeline by itself on startup? The scenario is that we want to fail on startup and exit if no endpoints are configured. – Johan Stenberg Apr 01 '19 at 10:32
  • @JohanStenberg `Configure` method runs one time on startup but the middleware just runs when a request comes into the application. The first time that the `Configure` method runs, if you inject `IHttpContextAccessor` to access HttpContext, the HttpContext will be null. So a request is necessary for this Middleware. – Moien Tajik Apr 01 '19 at 12:00
  • Also for your another requirement to fail if no endpoints configured, you can inject `IActionDescriptorCollectionProvider` and use `provider.ActionDescriptors.Items.Any()` to determine if any routes are configured as said in this answer: https://stackoverflow.com/a/46019311/6661314 – Moien Tajik Apr 01 '19 at 12:03