学无先后,达者为师

网站首页 编程语言 正文

Identity Server4/生产模式/证书/certificate/AddSigningCredential

作者:ChasingCode 更新时间: 2022-09-25 编程语言

开发时使用的 AddDeveloperSigningCredential(),不适合生产环境。

戳几字,简单使用PowerShell读取.CER 文件, 使用.NET X509Certificate2这个类,生成、读取、删除证书。

1. 打开cmd,然后输入powershell切换为powershell

 

2. 读取证书

输入 Get-ChildItem -Path cert:\CurrentUser\My 

 目前有3个证书

3.创建证书

输入 New-SelfSignedCertificate -Subject "CN=IDS4_Certificate" -CertStoreLocation cert:\CurrentUser\My -Provider "Microsoft Strong Cryptographic Provider"

名为 IDS4_Certificate

4.删除证书

输入 Remove-Item -Path ("cert:\CurrentUser\My\" + $cert.Thumbprint)

 (先试试增 删 查 这几步骤,后面就不重复了)

重点部分

5. 导出秘钥文件

a. 根据以上步骤先创建一个证书,名为 IDS4_Certificate, 输入

New-SelfSignedCertificate -Subject "CN=IDS4_Certificate" -CertStoreLocation cert:\CurrentUser\My -Provider "Microsoft Strong Cryptographic Provider"

b. 加载刚生成的证书,输入

  $cert = Get-ChildItem -Path cert:\CurrentUser\My\(your certificate thumbprint)

c.导出公钥到项目文件夹,输入

Export-Certificate -Type CERT -Cert $cert -FilePath "./publickey.cer"

d.导出私钥到项目文件夹

输入 $cred = Get-Credential 配置秘钥

 输入  Export-PfxCertificate -Cert $cert -Password $cred.Password -FilePath "./private.pfx"

Finish

配置identity server4 使用生成的证书

private readonly IConfiguration _configuration;
private readonly IHostEnvironment _environment;
private readonly IWebHostEnvironment _webHostEnv;

public Startup(IConfiguration configuration, IHostEnvironment environment, IWebHostEnvironment webHostEnvironment)
{
   _configuration = configuration;
   _environment = environment;
   _webHostEnv = webHostEnvironment;
}



IIdentityServerBuilder identityServerBuilder = services.AddIdentityServer();

//开发环境时
if (_environment.IsDevelopment())
{
  identityServerBuilder.AddDeveloperSigningCredential(); //配置临时凭据
}
else
{
  string certPath = Path.Combine(_webHostEnv.ContentRootPath, "private.pfx");
  var certificate = new X509Certificate2(certPath, "test");
  identityServerBuilder.AddSigningCredential(certificate);
}

如果有用请点赞,转载请说明出处,谢谢!!

原文链接:https://blog.csdn.net/m0_62367247/article/details/127033649

栏目分类
最近更新