asp.net core 2使用本地https证书

不得不吐槽, 国内的各种开发资料网站已经... 是黄了吗? 还是百度已经黄了?

今天打开开发的asp.net core2.几的项目, 一F5运行后浏览器说无法提供安全连接, 大意就是https证书不行了, 我也不知道为什么突然给我来这么一出, 昨天还好好的. 然后反正我用百度搜了好久, 来来回回就是csdn啊cnblog啊和一些其它记不行名字的网站, 各种资料全是相互抄, 虽然我浏览了好几个站点, 但是我其实只看到了最多3份资料.

屁话就不说了, 以下是内容:

先在PowerShell里运行以下, 生成证书:

# setup certificate properties including the commonName (DNSName) property for Chrome 58+
$certificate = New-SelfSignedCertificate `
    -Subject localhost `
    -DnsName localhost `
    -KeyAlgorithm RSA `
    -KeyLength 2048 `
    -NotBefore (Get-Date) `
    -NotAfter (Get-Date).AddYears(2) `
    -CertStoreLocation "cert:CurrentUser\My" `
    -FriendlyName "Localhost Certificate for .NET Core" `
    -HashAlgorithm SHA256 `
    -KeyUsage DigitalSignature, KeyEncipherment, DataEncipherment `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1") 
$certificatePath = 'Cert:\CurrentUser\My\' + ($certificate.ThumbPrint)  

# create temporary certificate path
$tmpPath = "C:\tmp"
If(!(test-path $tmpPath))
{
New-Item -ItemType Directory -Force -Path $tmpPath
}

# set certificate password here
$pfxPassword = ConvertTo-SecureString -String "YourSecurePassword" -Force -AsPlainText
$pfxFilePath = "c:\tmp\localhost.pfx"
$cerFilePath = "c:\tmp\localhost.cer"

# create pfx certificate
Export-PfxCertificate -Cert $certificatePath -FilePath $pfxFilePath -Password $pfxPassword
Export-Certificate -Cert $certificatePath -FilePath $cerFilePath

# import the pfx certificate
Import-PfxCertificate -FilePath $pfxFilePath Cert:\LocalMachine\My -Password $pfxPassword -Exportable

# trust the certificate by importing the pfx certificate into your trusted root
Import-Certificate -FilePath $cerFilePath -CertStoreLocation Cert:\CurrentUser\Root

# optionally delete the physical certificates (don’t delete the pfx file as you need to copy this to your app directory)
# Remove-Item $pfxFilePath
Remove-Item $cerFilePath

2, copy到项目根目录

3, 根目录下放如下文件:

certificate.json:

{
  "certificateSettings": {
    "fileName": "localhost.pfx",
    "password": "YourSecurePassword"
  }
}

3, 修改以下源码文件:

Programe.cs:

public class Program
{
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddEnvironmentVariables()
            .AddJsonFile("certificate.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"certificate.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true)
            .Build();

        var certificateSettings = config.GetSection("certificateSettings");
        string certificateFileName = certificateSettings.GetValue<string>("filename");
        string certificatePassword = certificateSettings.GetValue<string>("password");

        var certificate = new X509Certificate2(certificateFileName, certificatePassword);
        
        var host = new WebHostBuilder()
            .UseKestrel(
                options =>
                {
                    options.AddServerHeader = false;
                    options.Listen(IPAddress.Loopback, 44321, listenOptions =>
                    {
                        listenOptions.UseHttps(certificate);
                    });
                }
            )
            .UseConfiguration(config)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseUrls("https://localhost:44321")
            .Build();

        host.Run();
    }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddMvc(
        options =>
        {
            options.SslPort = 44321;
            options.Filters.Add(new RequireHttpsAttribute());
        }
    );

    services.AddAntiforgery(
        options =>
        {
            options.Cookie.Name = "_af";
            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.HeaderName = "X-XSRF-TOKEN";
        }
    );

    // ...
}

来源英文网站:https://www.humankode.com/asp-net-core/develop-locally-with-https-self-signed-certificates-and-asp-net-core