How would you implement Server Name Indication (SNI)-based certificate selection in Kestrel, serving different TLS certificates for different hostnames on the same IP/port?
Short answer
Kestrel's ServerCertificateSelector delegate (set via ConfigureHttpsDefaults or per-listener HttpsOptions) is invoked during the TLS handshake with the requested hostname (from the SNI extension the client sends before encryption begins), letting you dynamically return the…
Advertisement
AModel answer
Kestrel's ServerCertificateSelector delegate (set via ConfigureHttpsDefaults or per-listener HttpsOptions) is invoked during the TLS handshake with the requested hostname (from the SNI extension the client sends before encryption begins), letting you dynamically return the appropriate certificate for that specific hostname -- essential for multi-tenant applications hosting many custom domains on shared infrastructure, where provisioning a dedicated IP/port per domain wouldn't be practical.
builder.WebHost.ConfigureKestrel(options => {
options.ConfigureHttpsDefaults(httpsOptions => {
httpsOptions.ServerCertificateSelector = (connectionContext, hostName) => {
return _certificateStore.GetCertificateForHostname(hostName);
};
});
});Real-world example
A multi-tenant SaaS platform serving hundreds of customer custom domains (each with their own TLS certificate) on a single shared IP address implements SNI-based certificate selection, dynamically returning the correct tenant-specific certificate at the TLS handshake stage based on the hostname the client is connecting to.
Likely follow-ups
- How do you handle a client that doesn't support SNI (very old browsers/clients)?
- How would you efficiently cache and refresh certificates in the ServerCertificateSelector delegate to avoid expensive lookups on every handshake?
Related topics