From b9a9ec9305d16bb38ee943ddf348c89c0de0fcd6 Mon Sep 17 00:00:00 2001 From: Javier Calvarro Nelson Date: Fri, 19 May 2017 12:10:33 -0700 Subject: [PATCH] Add support for a default SSL certificate in development When the ssl certificate specified is 'localhost' and no certificate has been explicitly specified in the certificates section, fallback to a certificate with 'CN=localhost' (ASP.NET Core SSL developer certificate) in the current user store and if not found, an ssl certificate with 'CN=localhost' on the current machine (IIS Express developer certificate) --- .../KestrelServerOptionsSetup.cs | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.AspNetCore/KestrelServerOptionsSetup.cs b/src/Microsoft.AspNetCore/KestrelServerOptionsSetup.cs index a76e7f6c85..c36bf2f59a 100644 --- a/src/Microsoft.AspNetCore/KestrelServerOptionsSetup.cs +++ b/src/Microsoft.AspNetCore/KestrelServerOptionsSetup.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; @@ -15,6 +16,9 @@ namespace Microsoft.AspNetCore { internal class KestrelServerOptionsSetup : IConfigureOptions { + private const string DefaultCertificateSubjectName = "CN=localhost"; + private const string DevelopmentSSLCertificateName = "localhost"; + private readonly IHostingEnvironment _hostingEnvironment; private readonly IConfiguration _configurationRoot; private readonly ILoggerFactory _loggerFactory; @@ -65,13 +69,27 @@ namespace Microsoft.AspNetCore options.Listen(address, port, listenOptions => { var certificateConfig = endPoint.GetSection("Certificate"); - X509Certificate2 certificate; - + X509Certificate2 certificate = null; if (certificateConfig.Exists()) { try { - certificate = certificateLoader.Load(certificateConfig).FirstOrDefault(); + try + { + certificate = certificateLoader.Load(certificateConfig).FirstOrDefault(); + } + catch (KeyNotFoundException) when (certificateConfig.Value.Equals(DevelopmentSSLCertificateName, StringComparison.Ordinal) && _hostingEnvironment.IsDevelopment()) + { + var storeLoader = new CertificateStoreLoader(); + certificate = storeLoader.Load(DefaultCertificateSubjectName, "My", StoreLocation.CurrentUser, validOnly: false) ?? + storeLoader.Load(DefaultCertificateSubjectName, "My", StoreLocation.LocalMachine, validOnly: false); + + if (certificate == null) + { + var logger = _loggerFactory.CreateLogger("Microsoft.AspNetCore.KestrelOptionsSetup"); + logger.LogError("No HTTPS certificate was found for development. For information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054."); + } + } if (certificate == null) {