一、生成證書
mkcert 是一個簡單的工具,用于制作本地信任的開發證書。它不需要配置。
mkcert官方倉庫地址:GitHub - FiloSottile/mkcert: A simple zero-config tool to make locally trusted development certificates with any names you'd like.
簡化我們在本地搭建 https 環境的復雜性,無需操作繁雜的?openssl?實現自簽證書了,這個工具就可以幫助我們自簽證書,在本機使用還會自動信任 CA,非常方便。
下載安裝
下載地址:Releases · FiloSottile/mkcert · GitHub
?
安裝mkcert。將CA證書加入本地可信CA,使用此命令,就能幫助我們將mkcert使用的根證書加入了本地可信CA中,以后由該CA簽發的證書在本地都是可信的。下載后到下載目錄中安裝:?
mkcert-v1.4.4-windows-amd64.exe -install
?
?安裝成功成功。提示創建一個新的本地CA,本地CA現在已安裝在系統信任存儲中。
查看根證書位置
如果你想查看根證書位置,可以輸入命令:
?
生成自簽證書
直接跟多個要簽發的域名或 ip 就行了,比如簽發一個僅本機訪問的證書(可以通過127.0.0.1
和localhost
,以及 ipv6 地址::1
訪問):
mkcert-v1.4.4-windows-amd64.exe localhost 127.0.0.1 ::1 192.168.2.25
?
在mkcert軟件同目錄下,生成了自簽證書。如圖所示:?
?
二、NET 8?kestrel 使用證書
證書復制到wwwoort下
例如wwwoort/pem下
Program.cs的編輯代碼
public static IHostBuilder CreateWebHostBuilder(string[] args)
{//讀取證書var rootpath = Directory.GetCurrentDirectory();var certPem = File.ReadAllText(rootpath + "/wwwroot/pem/localhost+3.pem");var keyPem = File.ReadAllText(rootpath + "/wwwroot/pem/localhost+3-key.pem");var x509 = X509Certificate2.CreateFromPem(certPem, keyPem);returnHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{config.AddInMemoryCollection(new Dictionary<string, string> { { "HostRoot", hostingContext.HostingEnvironment.ContentRootPath } });}).ConfigureLogging((hostingContext, logging) =>{logging.ClearProviders();logging.AddConsole();logging.AddWTMLogger();}).ConfigureWebHostDefaults(webBuilder =>{webBuilder.ConfigureKestrel(serverOptions =>{//https 5001serverOptions.ListenAnyIP(5001, listenOptions =>{listenOptions.UseHttps(x509);});//http 5000 serverOptions.ListenAnyIP(5000);});webBuilder.UseStartup<Startup>();});
}
完成https自簽名證書配置。