Enforcing SSL in an ASP.NET Core app
This document shows how to:
- Require SSL for all requests (HTTPS requests only).
- Redirect all HTTP requests to HTTPS.
- Set up IIS Express to use SSL/HTTPS.
Require SSL
The RequireHttpsAttribute is used to require SSL. You can decorate controllers or methods with this attribute or you can apply it globally as shown below:
Add the following code to ConfigureServices
in Startup
:
// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
The highlighted code above requires all requests use HTTPS
, therefore HTTP requests are ignored. The following highlighted code redirects all HTTP requests to HTTPS:
// Requires using Microsoft.AspNetCore.Rewrite;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var options = new RewriteOptions()
.AddRedirectToHttps();
See URL Rewriting Middleware for more information.
Requiring HTTPS globally (options.Filters.Add(new RequireHttpsAttribute());
) is a security best practice. Applying the [RequireHttps]
to controllers has the drawback that you're not guaranteed new controllers added to you project will get this protection.
Set up IIS Express for SSL/HTTPS
- In Solution Explorer, right click the project and select Properties.
- On the left pane, select Debug.
- Check Enable SSL
- Copy the SSL URL and paste it into the App URL