ASP.NET - HTTPS Redirection and HSTS Policies

HTTPS redirection and HSTS are security features in ASP.NET Core that ensure all communication between the browser and server happens over a secure connection. They protect data from being intercepted or modified during transit.


HTTPS Redirection
HTTPS redirection automatically sends users from an HTTP URL to the HTTPS version of the site. If a user types http://, the server responds by redirecting the request to https://. This ensures encrypted communication without requiring users to think about security details.


Why HTTPS Is Important
HTTPS encrypts data such as login details, form inputs and API responses. Without encryption, attackers can read or modify data on open networks. HTTPS protects user privacy and is required for modern browser features like secure cookies and HTTP/2.


What HSTS Does
HSTS (HTTP Strict Transport Security) tells the browser to always use HTTPS for a website, even if the user types HTTP manually. Once enabled, the browser remembers this rule and never sends insecure requests to that domain for a specified time period.


How HSTS Improves Security
HSTS prevents downgrade attacks where attackers force browsers to use HTTP instead of HTTPS. It also protects users on their very first visit after the policy is applied, ensuring secure access every time without redirection delays.


When to Use HSTS
HSTS should be enabled only in production environments where HTTPS is fully configured. During development, it is usually disabled to avoid browser caching issues that may block local testing.


Example

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Enable HTTPS redirection
app.UseHttpsRedirection();

// Enable HSTS only in production
if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.MapGet("/", () => "Secure connection enabled");
app.Run();

Behavior

  • HTTP requests are redirected to HTTPS

  • Browsers remember to use HTTPS automatically

  • Improves overall application security without changing endpoints