簡體   English   中英

如何創建簽名證書並在生產中的 IdentityServer4 中使用它?

[英]How to create a signing certificate and use it in IdentityServer4 in production?

IdentityServer4 文檔站點上的大多數(全部?)示例代碼使用AddDeveloperSigningCredential() ,但建議在生產中使用AddSigningCredential() 我花了比我想知道如何做到這一點更多的時間。

如何創建簽名證書並在生產中的 IdentityServer4 中使用它?

創建證書並添加到機器的證書存儲

我決定創建一個證書並將其添加到機器的證書存儲中。 Brock Allen 在這里有一篇 2015 年的博客文章,描述了如何使用 MakeCert 創建證書。 但是,根據Microsoft MakeCert 文檔,它現在已被棄用。 所以我決定改用 PowerShell New-SelfSignedCertificate 小程序( MS docs )。 我翻譯了 Brock 的 MakeCert 命令以使用 New-SelfSignedCertificate 參數,最后得到了這個 PowerShell 命令:

    New-SelfsignedCertificate -KeyExportPolicy Exportable -Subject "CN=MyIdsvCertificate" -KeySpec Signature -KeyAlgorithm RSA -KeyLength 2048 -HashAlgorithm SHA256 -CertStoreLocation "cert:\LocalMachine\My"

If you want to check the certificate has been installed correctly, from the Run prompt launch "mmc", go to File, "Add/Remove Snap-in", select "Certificates", click Add, select "Computer account", Next, “本地計算機”,完成,OK。 然后瀏覽到 Certificates\Personal\Certificates,應該有一個頒發給 MyIdsvCertificate。

授予證書權限

創建證書后,您需要授予任何 Windows 身份正在運行 IIS (或任何為您的 IdentityServer 應用程序服務)的讀取權限,否則當 IdentityServer 嘗試使用密鑰時,您會收到“密鑰集不存在”錯誤。 為此,請找到文件夾 %ALLUSERSPROFILE%\Microsoft\Crypto\RSA\MachineKeys 找到時間戳與您創建證書的時間相匹配的文件,然后授予對運行 IIS 的 Windows 身份的讀取訪問權限(無需其他任何內容)。 此問題 在 IdentityServer4 GitHub 問題論壇上進行了討論,並由 Brock Allen 和 Dominick Baier 進行了解釋。 如果您是像 Brock 或 Dominick 這樣的天才,那么這種解釋可能已經足夠了,但像我這樣的傻瓜可能會發現Microsoft 支持網站上為非常相似的問題提供的更清晰的解釋和解決方案更有用。

告訴 IdentityServer 使用證書

現在已經完成了艱苦的工作。 剩下的就是告訴 IdentityServer 在不開發時使用證書:

    public void ConfigureServices(IServiceCollection services)
    {
        // ...
        // Configure some awesome services
        // ...

        var identityServer = services.AddIdentityServer(...options...)...AddStuff()...;

        if (_env.IsDevelopment())
        {
            identityServer.AddDeveloperSigningCredential();
        }
        else
        {
            identityServer.AddSigningCredential("CN=MyIdsvCertificate");
        }

        // ...
        // Configure more awesome services
        // ...
    }

請注意,調用 AddSigningCredential() 時需要“CN=”位,這也花費了我一些時間。 我實際上是在運行時從配置文件中獲取名稱的,但我們不需要在此處將 go 納入這些細節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM