36

What is the recommend way to redirect to HTTPS all incoming requests that are not secure. Do I need to write a middleware component? If so, I couldn't figure out how to get the server name.

public class RedirectHttpMiddleware
{
    RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.IsSecure)
            await _next(context);
        else
        {
            var server = "";  // How do I get the server name?
            context.Response.Redirect("https://" + server + context.Request.Path);
        }
    }
}
2

12 Answers 12

44

You can use your own middleware class, but typically I just do something like this in my Startup configuration:

app.Use(async (context, next) =>
{
    if (context.Request.IsHttps)
    {
        await next();
    }
    else
    {
        var withHttps = Uri.UriSchemeHttps + Uri.SchemeDelimiter + context.Request.Uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Scheme, UriFormat.SafeUnescaped);
        context.Response.Redirect(withHttps);
    }
});

What this does is just grab the entire URL, query string and all, and use GetComponents to get everything except the scheme in the URL. Then the HTTPS scheme gets prepended to the components URL.

This will work with the full .NET Framework, for ASP.NET Core, you can do something like this:

app.Use(async (context, next) =>
{
    if (context.Request.IsHttps)
    {
        await next();
    }
    else
    {
        var withHttps = "https://" + context.Request.Host + context.Request.Path;
        context.Response.Redirect(withHttps);
    }
});

This appends the host and the path to the HTTPS scheme. You may want to add other components such as the query and hash, too.

10
  • You are correct, it did not work with core. But changing it to this worked: var withHttps = "https://" + context.Request.Host + context.Request.Path;
    – William
    Apr 6, 2015 at 20:15
  • With this being so simple, it does seem like there should be a simple .RequireHttps() in the built in library.
    – William
    Apr 6, 2015 at 20:17
  • 1
    @VartanSimonian you are correct, but ASP.NET doesn't know how IIS is configured - it can't really look up the HTTPS port without querying the IIS metabase (it may not even be running in IIS!) rather than hard code it, put it in a config.json file.
    – vcsjones
    May 10, 2015 at 2:47
  • 1
    If one wants to include the querystring in the redirect, then one can use: $"https://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}"
    – Andreas
    Nov 4, 2015 at 7:52
  • 1
    @Gabe I suspect you are hosting your app in Kestrel but terminating SSL with nginx / IIS / some other front end. In that case, you want to look at the X-Forwarded-Proto header instead of the IsHttps property.
    – vcsjones
    Apr 22, 2016 at 20:17
16

For .NET Core 2.0 and lower (official docs for 2.0):

Use the [RequireHttps] attribute/filter. You can either do this to your controllers:

[RequireHttps]
public class AccountController {
}

Or else add this in your Startup.cs in the ConfigureServices method:

services.Configure<MvcOptions>(options =>
{
    options.Filters.Add(new RequireHttpsAttribute());
}

Also, I just wanted to add that vcsjones' answer is also correct, but you need to be sure to add this code early on in your config, before any other Middleware/code that causes redirects. In my case, I added it just before I added the Identity Framework middleware.

2
  • 4
    The only slight downside to doing this with MVC is that it applies only to MVC. If say, you have services.UseStaticFiles() before MVC (as you should, static content shouldn't go through the MVC pipeline) then the redirect won't happen.
    – vcsjones
    Feb 16, 2016 at 15:34
  • Note that this answer is applicable to .NET Core 2.0 (docs) where as the answer below by @Yanga which shows how to use UseHttpsRedirection in .NET Core 2.1 and above.
    – harvzor
    Feb 26, 2019 at 17:44
12

The full answer is in number 1 but don't stop there setting up HTTPS, go the extra step:

1 - We then use the RequireHttpsAttribute to redirect to HTTPS and set the SSL port in the MVC options. We are also reading the SSL port from launchSettings.json but we only need this in Development mode.

2 - Use AddAntiforgery to require HTTPS on your anti-forgery tokens.

3 - Use the NWebsec.AspNetCore.Middleware NuGet package and UseHsts method to enable Strict Transport Security (HSTS) across the site. Don't forget to add the Preload below and submit your site to the HSTS Preload site. More information here and here.

4 - Use NWebsec.AspNetCore.Middleware NuGet package and the UseHpkp method to enable Public Key Pinning (HPKP) across the site. Note that if you make a mistake with this one you are essentially DoS'ing your site. More information here and here.

5 - Include the https scheme in any URL's used. Content Security Policy (CSP) HTTP header and Subresource Integrity (SRI) do not play nice when you imit the scheme in some browsers. It is better to be explicit about HTTPS. e.g.

<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js"></script>

6- Use the ASP.NET MVC Boilerplate Visual Studio project template to generate a project with all of this and much more built in. You can also view the code on GitHub.

After all of the above, your Startup class should look something like this:

public class Startup
{
    private readonly int? sslPort;

    public Startup(IHostingEnvironment hostingEnvironment)
    {
        if (hostingEnvironment.IsDevelopment())
        {
            var launchConfiguration = new ConfigurationBuilder()
                .SetBasePath(hostingEnvironment.ContentRootPath)
                .AddJsonFile(@"Properties\launchSettings.json")
                .Build();
            // During development we won't be using port 443.
            this.sslPort = launchConfiguration.GetValue<int>("iisSettings:iisExpress:sslPort");
        }
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddAntiforgery(options =>
            {
                options.RequireSsl = true;
            });
            .AddMvc(options =>
            {
                options.Filters.Add(new RequireHttpsAttribute());
                options.SslPort = sslPort;
            });
    }

    public void Configure(IApplicationBuilder application)
    {
        application
            .UseHsts(options => options.MaxAge(days: 18 * 7).IncludeSubdomains().Preload())
            .UseHpkp(options => options
                .Sha256Pins(
                    "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
                    "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=")
                .MaxAge(days: 18 * 7)
                .IncludeSubdomains())
            .UseCsp(options => options
                .UpgradeInsecureRequests(this.sslPort.HasValue ? this.sslPort.Value : 443))
            .UseMvc();
    }
}
0
3

If you want to grab the port when in a DEV enviroment in .NET Core, look at env.IsDevelopment() and conditionally grab the SSL port from launchSettings.json.

if (env.IsDevelopment())
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile(@"Properties/launchSettings.json", optional: false, reloadOnChange: true);
    var launchConfig = builder.Build();
    sslPort = launchConfig.GetValue<int>("iisSettings:iisExpress:sslPort");
}

`

After grabing the SSL port, then you can incorporate the port into the solution posted by @vcsjones.

3

AlwaysHttpsMiddleware.cs, inspired by RequiresHttpsAttribute.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

public class AlwaysHttpsMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.IsHttps)
        {
            await _next.Invoke(context);
        }
        else
        {
            var request = context.Request;

            // only redirect for GET requests, otherwise the browser might
            // not propagate the verb and request body correctly.

            if (!string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase))
            {
                context.Response.StatusCode = StatusCodes.Status403Forbidden;
                await context.Response.WriteAsync("This site requires HTTPS.");
            }
            else
            {
                var newUrl = string.Concat(
                    "https://",
                    request.Host.ToUriComponent(),
                    request.PathBase.ToUriComponent(),
                    request.Path.ToUriComponent(),
                    request.QueryString.ToUriComponent());

                context.Response.Redirect(newUrl);
            }
        }
    }
}

Startup.cs

public void Configure(IApplicationBuilder app)
{
    if (_env.IsProduction())
    {
        app.UseMiddleware<AlwaysHttpsMiddleware>();
    }
 }
2

I have modified a bit @vcsjones answer to use custom port in dev environment. Also credits to @long2know.

app.Use(async (context, next) =>
{
    var request = context.Request;

    if (request.IsHttps)
    {
        await next();
    }
    else
    {
        var devPort = Configuration.GetValue<int>("iisSettings:iisExpress:sslPort");

        var host = env.IsDevelopment() && devPort > 0
            ? new HostString(request.Host.Host, devPort)
            : new HostString(request.Host.Host);

        string newUrl = $"https://{host}{request.PathBase}{request.Path}{request.QueryString}";
        context.Response.Redirect(newUrl, true);
    }
});

This must appear before app.UseStaticFiles or app.UseMvc, otherwise it will be ignored.

Note that the port should be taken from launchSettings.json file so you should also add this file to ConfigurationBuilder in the Startup.cs:

.AddJsonFile(@"Properties/launchSettings.json", optional: false, reloadOnChange: true)

1

In ASP.NET Core 2.1 just use this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();   // <-- Add this !!!!!
    }

    app.UseHttpsRedirection(); // <-- Add this !!!!!
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseMvc();
}
0

There are some great answers here, but I needed a solution that would work with or without IIS and also not change the protocol during local debug. I added this just after adding AD auth to the pipeline in the Startup.Configure method. This is for the full framework. Other solutions here outline how to rebuild the URL for Core.

app.Use(async (context, next) =>
{
    if (context.Request.IsHttps || // Handles https straight to the server 
        context.Request.Headers["X-Forwarded-Proto"] == Uri.UriSchemeHttps || // Handles an IIS or Azure passthrough
        context.Request.Host.ToString().StartsWith("localhost",true, System.Globalization.CultureInfo.InvariantCulture) || // Ignore for localhost
        context.Request.Headers["X-Forwarded-Proto"].Contains( Uri.UriSchemeHttps )) // X-Forwarded-Proto can have multiple values if there are multiple proxies 
    {
        await next();
    }
    else
    {
        var withHttps = Uri.UriSchemeHttps + Uri.SchemeDelimiter + context.Request.Host + context.Request.Path + context.Request.QueryString;
        context.Response.Redirect(withHttps);
    }
});
0

In order to have your DOTNet Core application to run under HTTPS, there are three steps to follow:

  1. Navigate to your Application's launchSettings.json file and enter your desired https port from 44390-44399 enter image description here
  2. Edit your Startup.cs file. Enter the following code:

    services.Configure<MvcOptions>(options =>
    {
        options.SslPort = 44390;
        options.Filters.Add(new RequireHttpsAttribute());
    });
    

    enter image description here

  3. Right-Click on your Project Root Directory, from Solution Explorer and Select Properties. Check Enable SSL, Copy the SSL link and add it to the App URL area. enter image description here

    1. Launch the Application. It will always run under the HTTPS context.
1
  • An error occurred attempting to determine the process id of AwsomeApp.exe which is hosting your application. One or more errors occurred.
    – Chris
    Mar 7, 2017 at 11:44
0

One technique discussed at https://github.com/aspnet/KestrelHttpServer/issues/916 is adding this to your web.config:

<rewrite>
      <rules>
          <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAny">
              <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
          </rule>
      </rules>
</rewrite>
1
  • This answer makes the assumption that the .NET Core application is being hosted using IIS which makes use of web.config files. There's no mention of IIS in the question.
    – harvzor
    Feb 26, 2019 at 17:50
0

If you need permanent redirect from http:// to https:// at .net core project, just add this code to Startup.cs app.UseHttpsRedirection();

More info here https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-6.0&tabs=visual-studio

-1

I like attribute with compiler directive

#if !DEBUG
    [RequireHttps]
#endif
    public class HomeController : Controller
    {
    }
1
  • Downvoting because this answer is almost identical to Josh Mouch (but this answer was over a year late). Next time, consider editing a pre-existing answer.
    – harvzor
    Feb 26, 2019 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.