Windows IIS ASP.NET Core中創建和使用HTTPS自簽名證書


為什么要用Https就不說了。

第一步:創建自簽名的證書。在Windows下開啟PowerShell,將以下文字粘貼進去:

# setup certificate properties including the commonName (DNSName) property for Chrome 58+
$certificate = New-SelfSignedCertificate `
    -Subject 改成自己想要的標題不要帶亂七八糟的符號(安裝證書的時候會顯示這個) `
    -DnsName 友好域名 `
    -KeyAlgorithm RSA `
    -KeyLength 2048 `
    -NotBefore (Get-Date) `
    -NotAfter (Get-Date).AddYears(2) `
    -CertStoreLocation "cert:CurrentUser\My" `
    -FriendlyName "證書的友好名稱,在IIS指定的時候顯示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 "證書的密碼" -Force -AsPlainText
$pfxFilePath = "c:\tmp\證書的名稱.pfx"
$cerFilePath = "c:\tmp\證書的名稱.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

  把漢字部分修改成你想要的,然后運行一下,就可以在C:\tmp下面找到你的證書了,一般把它放在網站根目錄下即可。

二、站點配置(ASP.NET Core 2.1)

* public void ConfigureServices(IServiceCollection services) 部分:

services.AddMvc(options =>
{
options.Filters.Add(new RequireHttpsAttribute());//所有請求都使用HTTPS
})

* public void Configure(IApplicationBuilder app, IHostingEnvironment env) 部分:

var options = new RewriteOptions().AddRedirectToHttps();
app.UseRewriter(options);
app.UseHttpsRedirection();

三、IIS配置:

經過這幾步,你的網站就變成Https的了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM