Edit

Enforce HTTPS in ASP.NET Core

By David Galvan and Rick Anderson

To enforce incoming requests to your ASP.NET Core apps to use HTTPS/TLS, you can:

  • Require HTTPS for all requests.
  • Redirect all HTTP requests to HTTPS.

No API can prevent a client from sending sensitive data on the first request.

This article describes how to configure your ASP.NET Core apps to require HTTPS/TLS or redirect HTTP requests to HTTPS/TLS for secure interaction. Troubleshooting steps are provided for various platforms to resolve untrusted certificate issues.

API projects

Projects that use Web APIs should either:

  • Not listen on HTTP.
  • Close the connection with status code 400 (Bad Request) and not serve the request.

To disable HTTP redirection in an API, set the ASPNETCORE_URLS environment variable or use the --urls command line flag. For more information, see ASP.NET Core runtime environments and 8 ways to set the URLs for an ASP.NET Core app by Andrew Lock.

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 might not understand or obey redirects from HTTP to HTTPS, and they might send information over HTTP.

HSTS and API projects

The secure approach for HTTP Strict Transport Security (HSTS) protocol is to configure API projects to only listen to and respond over HTTPS.

Warning

The default API projects don't include HSTS because it's generally a browser only instruction. Other callers, such as phone or desktop apps, do not obey the instruction. Even within browsers, a single authenticated call to an API over HTTP has risks on insecure networks.

HTTP redirect to HTTPS (ERR_INVALID_REDIRECT on CORS preflight request)

When a request to an endpoint using HTTP is redirected to HTTPS with the UseHttpsRedirection method, the redirection fails with the ERR_INVALID_REDIRECT error on the CORS preflight request.

API projects can reject HTTP requests rather than use the UseHttpsRedirection method to redirect requests to HTTPS.

Require HTTPS

For production ASP.NET Core web apps, the following approach is recommended:

  • To redirect HTTP requests to HTTPS, use HTTPS redirection middleware (UseHttpsRedirection).

  • To send HSTS headers to clients, use HSTS middleware via the UseHsts method.

Note

Apps deployed in a reverse proxy configuration allow the proxy to handle connection security (HTTPS). If the proxy also handles HTTPS redirection, there's no need to use HTTPS redirection middleware. If the proxy server also handles writing HSTS headers (for example, native HSTS support in Internet Information Services (IIS) 10.0 version 1709 or later), then the app doesn't require HSTS middleware. For more information, see Opt-out of HTTPS/HSTS on project creation.

HTTPS redirection middleware (UseHttpsRedirection)

The following code calls the UseHttpsRedirection method in the Program.cs file:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

The preceding highlighted code:

The recommended approach is to use temporary redirects rather than permanent redirects. Link caching can cause unstable behavior in development environments. If you prefer to send a permanent redirect status code when the app is in a non-Development environment, see the Configure permanent redirects in production section. Use HSTS to signal to clients that only secure resource requests should be sent to the app (only in production).

Note

Don't confuse the HTTPS_PORT configuration key and ASPNETCORE_HTTPS_PORT environment variable, which set the port for HTTPS redirection middleware, with the HTTPS_PORTS configuration key and ASPNETCORE_HTTPS_PORTS environment variable, which set the ports for Kestrel/HTTP.sys endpoint configuration.

Port configuration

A port must be available for the middleware to redirect an insecure request to HTTPS. If no port is available:

  • Redirection to HTTPS doesn't occur.
  • The middleware logs the warning Failed to determine the https port for redirect.

Specify the HTTPS port by using any of the following approaches:

  • Set HttpsRedirectionOptions.HttpsPort.

  • Set the https_port host setting:

    • In host configuration.

    • By setting the ASPNETCORE_HTTPS_PORT environment variable.

    • By adding a top-level entry in the appsettings.json file:

      {
        "https_port": 443,
        "Logging": {
          "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
          }
        },
        "AllowedHosts": "*"
      }
      
  • Indicate a port with the secure scheme by using the ASPNETCORE_URLS environment variable. The environment variable configures the server. The middleware indirectly discovers the HTTPS port via IServerAddressesFeature. This approach doesn't work in reverse proxy deployments.

  • The ASP.NET Core web templates set an HTTPS URL in the Properties/launchsettings.json file for both Kestrel and IIS Express. The launchsettings.json file is used on the local machine only.

  • Configure an HTTPS URL endpoint for a public-facing edge deployment of Kestrel server or HTTP.sys server. Only one HTTPS port is used by the app. The middleware discovers the port via IServerAddressesFeature.

Note

When an app runs in a reverse proxy configuration, IServerAddressesFeature isn't available. Set the port by using one of the other approaches described in this section.

Edge deployments

When Kestrel or HTTP.sys is used as a public-facing edge server, Kestrel or HTTP.sys must be configured to listen on both:

  • The secure port where the client is redirected (typically, 443 in production and 5001 in development).
  • The insecure port (typically, 80 in production and 5000 in development).

The insecure port must be accessible by the client for the app to receive an insecure request and redirect the client to the secure port.

For more information, see Kestrel endpoint configuration or HTTP.sys web server implementation in ASP.NET Core.

Deployment scenarios

Any firewall between the client and server must also have communication ports open for traffic.

If requests are forwarded in a reverse proxy configuration, use forwarded headers middleware before calling HTTPS redirection middleware. Forwarded headers middleware updates the Request.Scheme by using the X-Forwarded-Proto header. The middleware permits redirect URIs and other security policies to work correctly. When forwarded headers middleware isn't used, the back-end app might not receive the correct scheme and get caught in a redirect loop. A common end user error message is there are too many redirects.

When deploying to Azure App Service, follow the guidance in Enable HTTPS for a custom domain in Azure App Service.

Options

The following highlighted code calls the AddHttpsRedirection method to configure middleware options:

using static Microsoft.AspNetCore.Http.StatusCodes;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddHsts(options =>
{
    options.Preload = true;
    options.IncludeSubDomains = true;
    options.MaxAge = TimeSpan.FromDays(60);
    options.ExcludedHosts.Add("example.com");
    options.ExcludedHosts.Add("www.example.com");
});

builder.Services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = Status307TemporaryRedirect;
    options.HttpsPort = 5001;
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

Calling AddHttpsRedirection is only necessary to change the values of HttpsPort or RedirectStatusCode.

The preceding highlighted code:

Configure permanent redirects in production

The middleware defaults to sending a Status307TemporaryRedirect code with all redirects. If you prefer to send a permanent redirect status code when the app is in a non-Development environment, wrap the middleware options configuration in a conditional check for a non-Development environment.

The following code shows configuration of services in the Program.cs file:

using static Microsoft.AspNetCore.Http.StatusCodes;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

if (!builder.Environment.IsDevelopment())
{
    builder.Services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = Status308PermanentRedirect;
        options.HttpsPort = 443;
    });
}

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");

    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

HTTPS redirection middleware alternative approach

An alternative to using HTTPS redirection middleware (with the UseHttpsRedirection method) is to use URL rewriting middleware (via the AddRedirectToHttps method). AddRedirectToHttps can also set the status code and port when the redirect is executed. For more information, see URL rewriting middleware.

When the app redirects to HTTPS without the requirement for other redirect rules, the recommendation is to use HTTPS redirection middleware (UseHttpsRedirection) as described in this article.

HTTP Strict Transport Security (HSTS) protocol

Per OWASP, HSTS is an opt-in security enhancement specified by a web app via a response header. When a browser that supports HSTS receives this header:

  • The browser stores configuration for the domain that prevents sending any communication over HTTP. The browser forces all communication over HTTPS.
  • The browser prevents the user from using untrusted or invalid certificates. The browser disables prompts that allow a user to temporarily trust such a certificate.

Because the client enforces HSTS, there are some limitations:

  • The client must support HSTS.
  • HSTS requires at least one successful HTTPS request to establish the HSTS policy.
  • The application must check every HTTP request and redirect or reject the HTTP request.

ASP.NET Core implements HSTS with the UseHsts extension method. The following code calls UseHsts when the app isn't in development mode:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

UseHsts isn't recommended in development because the HSTS settings are highly cacheable by browsers. By default, UseHsts excludes the local loopback address.

For production environments that are implementing HTTPS for the first time, set the initial HstsOptions.MaxAge property value to a small amount by using one of the TimeSpan methods. Set the value from hours to no more than a single day, in case you need to revert the HTTPS infrastructure to HTTP. After you're confident in the sustainability of the HTTPS configuration, increase the HSTS max-age value (commonly, one year).

The following highlighted code:

using static Microsoft.AspNetCore.Http.StatusCodes;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddHsts(options =>
{
    options.Preload = true;
    options.IncludeSubDomains = true;
    options.MaxAge = TimeSpan.FromDays(60);
    options.ExcludedHosts.Add("example.com");
    options.ExcludedHosts.Add("www.example.com");
});

builder.Services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = Status307TemporaryRedirect;
    options.HttpsPort = 5001;
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

UseHsts excludes the following loopback hosts:

  • localhost: The IPv4 loopback address.
  • 127.0.0.1: The IPv4 loopback address.
  • [::1]: The IPv6 loopback address.

Opt out of HTTPS/HSTS on project creation

In some back-end service scenarios where connection security is handled at the public-facing edge of the network, configuring connection security at each node isn't required. Web apps that are generated from the templates in Visual Studio or from the dotnet new command enable HTTPS redirection and HSTS. For deployments that don't require these scenarios, you can opt out of HTTPS/HSTS when the app is created from the template.

To opt out of HTTPS/HSTS:

When you create a new ASP.NET Core web app, unselect the Configure for HTTPS option:

Screenshot that shows the 'Create a new ASP.NET Core web application' dialog in Visual Studio, and 'Configure for HTTPS' unselected.

Trust the ASP.NET Core HTTPS development certificate

The .NET SDK includes an HTTPS development certificate. The certificate is installed as part of the first-run experience. For example, the dotnet --info command produces a variation of the following output:

ASP.NET Core
------------
Successfully installed the ASP.NET Core HTTPS Development Certificate.
To trust the certificate run 'dotnet dev-certs https --trust' (Windows and macOS only).
For establishing trust on other platforms refer to the platform specific documentation.
For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.

Installing the .NET SDK installs the ASP.NET Core HTTPS development certificate to the local user certificate store. The certificate is installed, but it isn't trusted. To trust the certificate, perform the one-time step to run the dotnet dev-certs tool:

dotnet dev-certs https --trust

The following command provides help on the dotnet dev-certs tool:

dotnet dev-certs https --help

Warning

Don't create a development certificate in an environment planned for redistribution, such as a container image or virtual machine. This scenario can lead to spoofing and elevation of privilege. To help prevent this situation, set the DOTNET_GENERATE_ASPNET_CERTIFICATE environment variable to false before calling the .NET CLI for the first time. This approach skips the automatic generation of the ASP.NET Core development certificate during the CLI's first-run experience.

Set up developer certificate for Docker

To configure the developer certificate for Docker, see GitHub dotnet/aspnetcore.docs issue #6199 - How to set up the dev certificate when using Docker in development.

Linux-specific considerations

Linux distributions differ substantially in how they mark certificates as trusted.

The dotnet dev-certs tool is expected to be broadly applicable, but official support is available for Ubuntu and Fedora only. The support specifically aims to ensure trust in Firefox and Chromium-based browsers (Microsoft Edge, Chrome, and Chromium).

Dependencies

  • To establish OpenSSL trust, the openssl tool must be on the path.
  • To establish browser trust (for example in Microsoft Edge or Firefox), the certutil tool must be on the path.

OpenSSL trust

When an ASP.NET Core development certificate is trusted, the certificate is exported to a folder in the current user's home directory. To have OpenSSL (and clients that consume it) pick up this folder, you need to set the SSL_CERT_DIR environment variable. You can set the variable in a single session by running a command like export SSL_CERT_DIR=$HOME/.aspnet/dev-certs/trust:/usr/lib/ssl/certs (the exact value is in the output when --verbose is passed) or by adding it your (distro- and shell-specific) configuration file (for example .profile).

This approach is required to make tools like curl trust the development certificate. Alternatively, you can pass -CAfile or -CApath to each individual curl invocation.

Note

Requires 1.1.1h or later or 3.0.0 or later, depending on which major version you're using.

If OpenSSL trust gets into a bad state (for example if dotnet dev-certs https --clean fails to remove it), you can frequently resolve the situation by using the c_rehash tool.

Overrides

If you're using another browser with its own Network Security Services (NSS) store, you can use the DOTNET_DEV_CERTS_NSSDB_PATHS environment variable to specify a colon-delimited list of NSS directories (for example, the directory containing cert9.db). You can then add the development certificate location to the list in the variable.

If you store the certificates you want OpenSSL to trust in a specific directory, you can use the DOTNET_DEV_CERTS_OPENSSL_CERTIFICATE_DIRECTORY environment variable to indicate the certificate location.

Warning

If you set either variable, be sure to set the same values each time trust is updated. If the values change, the tool doesn't know about certificates in the former locations (for example, during certificate cleanup).

Using sudo

As on other platforms, development certificates are stored and trusted separately for each user.

If you run dotnet dev-certs as a different user (for example, by using sudo), then that specific user (for example root) trusts the development certificate.

Trust the certificate from Windows Subsystem for Linux

Run the trust command inside WSL. When WSL interop is enabled, it also attempts to add the public certificate to the Windows Current User Root certificate store. Check the command output for trust failures and any required Linux configuration.

Trust HTTPS certificate on Linux with linux-dev-certs

linux-dev-certs is an open-source, community-supported, .NET global tool that provides a convenient way to create and trust a developer certificate on Linux. Microsoft doesn't maintain or support the tool.

The following commands install the tool and create a trusted developer certificate:

dotnet tool update -g linux-dev-certs
dotnet linux-dev-certs install

For more information or to report issues, see the linux-dev-certs GitHub repository.

Trust the certificate on SUSE Linux Enterprise Server (SLES) and openSUSE

dotnet dev-certs https --trust isn't officially supported on SLES. Use the following steps to export the development certificate and trust it in Chromium-based browsers, Firefox, and command-line tools. The steps were verified on SLES 15 SP7 and openSUSE Leap 15.6.

Warning

The following instructions are intended for development purposes only. Don't use the development certificate in a production environment.

Note

Adding the certificate to the system trust store (/etc/pki/trust/anchors/ followed by update-ca-certificates) doesn't work for the development certificate. The certificate isn't a certificate authority (CA:FALSE), so p11-kit lists it as an anchor but doesn't include it in the generated bundles, and OpenSSL continues to reject it. Trust it per application as shown below instead.

Install dependencies

The certutil tool used to manage browser certificate stores is provided by the mozilla-nss-tools package:

sudo zypper install mozilla-nss-tools openssl

Export the development certificate

Replace ${CertificateDirectory} with a directory outside your source repositories, for example $HOME/.aspnet/https:

mkdir -p ${CertificateDirectory}
dotnet dev-certs https -ep ${CertificateDirectory}/aspnetcore.crt --format PEM --no-password

Trust the certificate in Chromium-based browsers (Microsoft Edge, Chrome, Chromium)

certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n aspnetcore -i ${CertificateDirectory}/aspnetcore.crt

If $HOME/.pki/nssdb doesn't exist yet, create it first with certutil -d sql:$HOME/.pki/nssdb -N --empty-password. Restart the browser after importing.

Trust the certificate in Firefox

Replace ${UserProfile} with the name of your Firefox profile directory (see about:profiles in Firefox):

certutil -d sql:$HOME/.mozilla/firefox/${UserProfile}/ -A -t "C,," -n aspnetcore -i ${CertificateDirectory}/aspnetcore.crt

Trust the certificate in curl and other OpenSSL clients

Pass the exported certificate explicitly:

curl --cacert ${CertificateDirectory}/aspnetcore.crt https://localhost:5001

Alternatively, point SSL_CERT_DIR at a directory that contains the certificate as described in OpenSSL trust.

Remove the development certificate

certutil -d sql:$HOME/.pki/nssdb -D -n aspnetcore
certutil -d sql:$HOME/.mozilla/firefox/${UserProfile}/ -D -n aspnetcore
rm ${CertificateDirectory}/aspnetcore.crt
dotnet dev-certs https --clean

Trust the certificate on Red Hat Enterprise Linux (RHEL)

dotnet dev-certs https --trust isn't officially supported on RHEL. The following steps mirror the SLES instructions, adapted for RHEL package names.

Warning

The following instructions are intended for development purposes only. Don't use the development certificate in a production environment.

Note

As on SLES, adding the certificate to the system trust store (/etc/pki/ca-trust/source/anchors/ followed by update-ca-trust) doesn't work for the development certificate. The certificate isn't a certificate authority (CA:FALSE), so trust it per application as shown below instead.

Install dependencies

The certutil tool used to manage browser certificate stores is provided by the nss-tools package:

sudo dnf install nss-tools openssl

Export the development certificate

Replace ${CertificateDirectory} with a directory outside your source repositories, for example $HOME/.aspnet/https:

mkdir -p ${CertificateDirectory}
dotnet dev-certs https -ep ${CertificateDirectory}/aspnetcore.crt --format PEM --no-password

Trust the certificate in Chromium-based browsers (Microsoft Edge, Chrome, Chromium)

certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n aspnetcore -i ${CertificateDirectory}/aspnetcore.crt

If $HOME/.pki/nssdb doesn't exist yet, create it first with certutil -d sql:$HOME/.pki/nssdb -N --empty-password. Restart the browser after importing.

Trust the certificate in Firefox

Replace ${UserProfile} with the name of your Firefox profile directory (see about:profiles in Firefox):

certutil -d sql:$HOME/.mozilla/firefox/${UserProfile}/ -A -t "C,," -n aspnetcore -i ${CertificateDirectory}/aspnetcore.crt

Trust the certificate in curl and other OpenSSL clients

Pass the exported certificate explicitly:

curl --cacert ${CertificateDirectory}/aspnetcore.crt https://localhost:5001

Alternatively, create an OpenSSL hashed certificate directory and point SSL_CERT_DIR at it:

mkdir -p ${CertificateDirectory}/certs
cp ${CertificateDirectory}/aspnetcore.crt ${CertificateDirectory}/certs/
openssl rehash ${CertificateDirectory}/certs
export SSL_CERT_DIR=${CertificateDirectory}/certs

Remove the development certificate

certutil -d sql:$HOME/.pki/nssdb -D -n aspnetcore
certutil -d sql:$HOME/.mozilla/firefox/${UserProfile}/ -D -n aspnetcore
rm ${CertificateDirectory}/aspnetcore.crt
dotnet dev-certs https --clean

Troubleshoot certificate problems (certificate not trusted)

Sometimes when an ASP.NET Core HTTPS development certificate is installed and trusted, the browser warns that the certificate is untrusted. The following sections provide help for troubleshooting this issue.

The ASP.NET Core HTTPS development certificate is used by Kestrel.

To repair the IIS Express certificate, see Stack Overflow issue #20036984 / answer #20048613 - How do I restore a missing IIS Express SSL Certificate?

Expired development certificate (NET::ERR_CERT_DATE_INVALID)

ASP.NET Core development certificates are valid for a limited period (typically 12 months). When a development certificate expires, browsers and client tools report errors such as NET::ERR_CERT_DATE_INVALID or SEC_ERROR_EXPIRED_CERTIFICATE.

To renew an expired development certificate:

  1. Remove the expired certificates and create a new trusted development certificate:

    dotnet dev-certs https --clean
    dotnet dev-certs https --trust
    
  2. If your development environment exports or mounts the certificate file to disk, such as in Docker containers, JavaScript Project System (JSPS) SPA projects, or Kestrel Certificates:Default:Path configurations:

    • Re-export the certificate: Export the new certificate to the expected file location. In the following example, the <path to certificate> placeholder is the path to the certificate .pfx file (for example, /etc/ssl/certs/myapp-dev.pfx), and the <password> placeholder is the password:

      dotnet dev-certs https -ep <path to certificate> -p <password>
      
    • Docker development: Delete the expired certificate file in %APPDATA%\ASP.NET\Https (Windows) or ~/.aspnet/https (Linux/macOS), regenerate the certificate using dotnet dev-certs https -ep ..., and restart the Docker container to mount the updated certificate.

    • SPA development: Delete the expired certificate files in %APPDATA%\ASP.NET\https or ~/.aspnet/https, such as <project-name>.pem and <project-name>.key. SPA development servers regenerate or re-export these files automatically upon startup, or export them using:

      dotnet dev-certs https --export-path <path to certificate> --format Pem --no-password
      
  3. Stop and restart the running application, including any dotnet run or Kestrel process. Kestrel loads the development certificate at startup; restarting the application ensures it loads the renewed certificate.

  4. Completely close all browser windows and restart your IDE, such as Visual Studio or Visual Studio Code, to clear cached SSL/TLS sessions.

All platforms - certificate not trusted

For all platforms, try to resolve the untrusted certificate issues with the following steps:

  1. Run the following commands:

    dotnet dev-certs https --clean
    dotnet dev-certs https --trust
    
  2. Close any open browser instances, and open the app in a new browser window.

    The browser cache stores whether a certificate is trusted. The close/open process helps to refresh the browser cache settings for certificates.

The dotnet dev-certs https commands usually solve most browser trust issues. If the dotnet dev-certs https --clean command fails and the browser still doesn't trust the certificate, try the platform-specific suggestions in the following sections.

Docker - certificate not trusted

If you're using Docker, try to resolve the issue with the following steps:

  1. Delete the C:\Users{USER}\AppData\Roaming\ASP.NET\Https folder.

  2. Clean the solution. Delete the bin and obj folders.

  3. Restart the development tool. For example, Visual Studio or Visual Studio Code.

Windows - certificate not trusted

If you're working in Windows, complete the following troubleshooting steps:

  1. Check the certificates in the certificate store. Look for a localhost certificate with the ASP.NET Core HTTPS development certificate friendly name in two folders:

    • Current User > Personal > Certificates
    • Current User > Trusted root certification authorities > Certificates
  2. Remove all certificates from both Personal and Trusted root certification authorities.

    Important

    Do not remove the IIS Express localhost certificate.

  3. Run the following commands:

    dotnet dev-certs https --clean
    dotnet dev-certs https --trust
    
  4. Close any open browser instances, and open the app in a new browser window.

OS X - certificate not trusted

If you're working with OS X, try to resolve the issue with the following steps:

  1. Open KeyChain Access, and then select the System keychain.

  2. Check for the presence of a localhost certificate.

  3. Confirm the certificate shows the plus (+) symbol on the icon, which indicates the certificate is trusted for all users.

  4. Remove the certificate from the system keychain.

  5. Run the following commands:

    dotnet dev-certs https --clean
    dotnet dev-certs https --trust
    
  6. Close any open browser instances, and open the app in a new browser window.

For more information about troubleshooting certificate issues with Visual Studio, see GitHub dotnet/aspnetcore issue #16892) - HTTPS Error using IIS Express.

Linux - certificate not trusted

If you're running Linux, follow these steps to troubleshoot the untrusted certificate:

  1. Confirm the certificate you're investigating is the user HTTPS developer certificate planned for use by the Kestrel server.

  2. Check the current user default HTTPS developer Kestrel certificate at the following location:

    ls -la ~/.dotnet/corefx/cryptography/x509stores/my
    

    The HTTPS developer Kestrel certificate file is the SHA1 thumbprint. When the file is deleted with the dotnet dev-certs https --clean command, the file is regenerated when needed with a different thumbprint.

  3. Verify the thumbprint of the exported certificate matches by running the following command:

    openssl x509 -noout -fingerprint -sha1 -inform pem -in /usr/local/share/ca-certificates/aspnet/https.crt
    

    If the certificate thumbprint doesn't match, investigate the following conditions:

    • Check if the certificate is old.

    • Check if the certificate is an exported developer certificate for the root user.

      • If it is, export the certificate.
  4. Check the root user certificate in the following folder:

    ls -la /root/.dotnet/corefx/cryptography/x509stores/my
    

IIS Express SSL certificate used with Visual Studio

To fix problems with the IIS Express certificate, select Repair in the Visual Studio installer. For more information, see GitHub dotnet/aspnetcore issue #16892) - HTTPS Error using IIS Express.

Group policy prevents trusting self-signed certificates

In some cases, group policy can prevent self-signed certificates from being trusted. For more information, see GitHub dotnet/aspnetcore issue #21173 - Error trusting HTTPS developer certificate.