skip to content

In ASP.NET Core 10's Kestrel:Endpoints configuration, how do you serve a different TLS certificate per host name on one HTTPS port, and what happens when nothing matches?

level: middleimportance: should knowfreq 30%

answer

  1. the name arrives in the TLS ClientHello
  2. an Sni subsection per endpoint
  3. exact, then *.suffix, then *
  4. Certificates:Default as the shared fallback
  5. no match: the handshake is refused

basics

~20 s

Add an Sni section under the endpoint, keyed by host name, each with its own Certificate (and optionally Protocols, SslProtocols, ClientCertificateMode). Kestrel tries an exact name, then the longest .suffix, then ""; with no match it refuses the TLS handshake.

solid answer

~40 s

A client sends the host name it wants in the TLS ClientHello (Server Name Indication), before any HTTP request exists. Kestrel can pick a certificate from that name: under `Kestrel:Endpoints:<name>` you add an `Sni` object whose keys are host names, each with a `Certificate` and, optionally, its own `Protocols`, `SslProtocols` and `ClientCertificateMode`. Lookup is an exact, case-insensitive match first, then wildcard entries such as `*.example.com` (longest suffix first), then a bare `*` entry. An SNI entry without its own certificate uses the endpoint's certificate. If nothing matches and there is no `*` entry, Kestrel aborts the handshake with an `AuthenticationException` and the client never sends a request. In code the equivalent is `HttpsConnectionAdapterOptions.ServerCertificateSelector`.

code

json · 20 lines
json
{
  "Kestrel": {
    "Endpoints": {
      "Ingest": {
        "Url": "https://*:8443",
        "Sni": {
          "ingest.example.com": {
            "Certificate": { "Path": "/certs/ingest.pem", "KeyPath": "/certs/ingest.key" }
          },
          "*.devices.example.com": {
            "Certificate": { "Subject": "devices.example.com", "Store": "My" }
          },
          "*": {
            "Certificate": { "Path": "/certs/fallback.pfx", "Password": "<from secret store>" }
          }
        }
      }
    }
  }
}

go deeper

for a junior

Recall that one HTTPS port can serve several certificates through SNI, configured as an Sni section under a Kestrel endpoint.

for a middle

Explain the matching order (exact, longest wildcard suffix, then *), the per-entry Certificate, Protocols, SslProtocols and ClientCertificateMode keys, and Certificates:Default.

for a senior

Show you would add a * entry deliberately, keep keys out of appsettings.json, rely on file watching for rotation, and switch to ServerCertificateSelector for dynamic tenants.

for a principal

Weigh terminating TLS per host name in Kestrel against terminating it at a shared edge, considering who owns certificates and rotation.

## Why a server needs the host name before HTTP One IP address and port can serve several host names, but TLS is negotiated **before** the HTTP request with its `Host` header is sent. The server therefore cannot read `Host` to choose a certificate. **Server Name Indication (SNI)** solves this: the client puts the host name it is connecting to in the TLS ClientHello, and the server picks a certificate from it. Kestrel exposes that choice through configuration and through code. ## Certificates in the `Kestrel` section Every HTTPS endpoint needs a server certificate. The `Certificate` object accepts two shapes: - **A file:** `Path` to a `.pfx` with `Password`, or `Path` to a PEM certificate plus `KeyPath` to its key (and `Password` if the key is encrypted). - **A certificate store entry:** `Subject`, `Store` (for example `My`), `Location` (`CurrentUser` unless you set `LocalMachine`) and `AllowInvalid`. An HTTPS endpoint that declares no certificate falls back to `Kestrel:Certificates:Default`; if that is absent, Kestrel tries the development certificate, and if none is found it fails at startup with "Unable to configure HTTPS endpoint. No server certificate was specified...". `WebApplication.CreateBuilder` loads the `Kestrel` section with reload-on-change enabled and watches certificate files it loaded by `Path`. Replacing a certificate file on disk, or editing the section, makes Kestrel reload the affected endpoints without a restart. ## The `Sni` subsection For the telemetry ingest service, one HTTPS port serves devices on `ingest.example.com`, a regional fleet under `*.devices.example.com`, and anything else with a catch-all certificate: ```json { "Kestrel": { "Endpoints": { "Ingest": { "Url": "https://*:8443", "Sni": { "ingest.example.com": { "Certificate": { "Path": "/certs/ingest.pem", "KeyPath": "/certs/ingest.key" }, "Protocols": "Http1AndHttp2" }, "*.devices.example.com": { "Certificate": { "Subject": "devices.example.com", "Store": "My" }, "ClientCertificateMode": "RequireCertificate" }, "*": { "Certificate": { "Path": "/certs/fallback.pfx", "Password": "<from secret store>" } } } } } } } ``` Each SNI entry may set: | Key | Effect | When omitted | |---|---|---| | `Certificate` | server certificate for that name | the endpoint's certificate (or `Certificates:Default`) | | `Protocols` | HTTP versions offered through ALPN | the endpoint's `Protocols` | | `SslProtocols` | allowed TLS versions | the endpoint's setting (OS default) | | `ClientCertificateMode` | whether a client certificate is requested or required | the endpoint's setting | ## How Kestrel matches a name For each new TLS connection: 1. If the client sent a name, Kestrel looks for an **exact** entry, ignoring case. 2. If none exists, it tries **wildcard** entries. `*.devices.example.com` is stored as the suffix `.devices.example.com`, so it matches `eu.devices.example.com` and `a.eu.devices.example.com`, but not `devices.example.com` itself. Longer suffixes are tried first. 3. If still nothing matches, or the client sent no name at all, the **`*`** entry is used. 4. If there is no `*` entry, Kestrel throws an `AuthenticationException` ("Connection refused because no SNI configuration section was found for '...'"). The handshake fails; the client sees a TLS error, never an HTTP status code. That last rule surprises people who expect the endpoint certificate to act as a fallback. It does so only for SNI entries that omit `Certificate`, not for unmatched names. Add `*` if unknown names must still be served. ## Doing it in code When certificates come from a vault or a cache, use a selector instead of configuration: ```csharp builder.WebHost.ConfigureKestrel(options => { options.ListenAnyIP(8443, listen => listen.UseHttps(https => { https.ServerCertificateSelector = (connection, name) => certificateCache.Find(name) ?? certificateCache.Fallback; })); }); ``` `ServerCertificateSelector` takes precedence over `ServerCertificate`, runs on every handshake (keep it fast and cached), and receives a null name when the client sent none. For full control of `SslServerAuthenticationOptions` per connection there is a `UseHttps` overload taking `TlsHandshakeCallbackOptions`, which is what the configuration-based SNI support uses internally. ## Client certificates per host name The `ClientCertificateMode` key per SNI entry lets one port treat callers differently. In the ingest service, devices under `*.devices.example.com` must present a client certificate (`RequireCertificate`), while dashboards calling `ingest.example.com` present none (`NoCertificate`, the default). The setting is applied during the handshake, so a device without a certificate is rejected before any endpoint code runs; validating which certificates are acceptable is then the job of certificate authentication in the app. ## Common mistakes - Putting the private key password in `appsettings.json` instead of a secret source. - Expecting `*.example.com` to cover the apex `example.com`. - Forgetting `*` and then debugging "connection reset" reports from clients that send an IP literal, which carries no SNI name.

  • Does the endpoint-level Certificate act as a fallback when a host name matches no SNI entry?
    No. The endpoint certificate is used only by SNI entries that leave out their own `Certificate`. An unmatched name with no `*` entry makes Kestrel refuse the handshake with an `AuthenticationException`, so the client gets a TLS failure rather than an HTTP response.
  • How do you rotate a certificate on a running Kestrel server configured through appsettings.json?
    With `WebApplication.CreateBuilder`, the `Kestrel` section is loaded with reload-on-change, and certificate files referenced by `Path` are watched. Replacing the file, or changing the section, makes Kestrel reload the configuration and rebind the affected endpoints, so new connections are served with the new certificate.
  • When would you prefer ServerCertificateSelector over the Sni section?
    When the set of host names is dynamic, for example tenants added at runtime with certificates from a vault. The selector runs per handshake and can consult a cache, while the `Sni` section needs a configuration change for every new name.

  • Kestrel reads the Host header to choose the certificate.
  • An unmatched host name silently falls back to the endpoint certificate.
  • *.example.com also covers the bare example.com.
  • A missing SNI match returns HTTP 421 Misdirected Request.
  • Changing a certificate file always requires restarting the app.