IdentityServer4 生产环境添加证书

对于Token签名,需要一对公钥和私钥,不过IdentityServer为开发者提供了一个AddDeveloperSigningCredential()方法,它会帮我们搞定这个事,并默认存到硬盘中。当切换到生产环境时,还是得使用正儿八经的证书,更换为使用AddSigningCredential()方法。

在生产环境,通过OpenSSL来生成,首先去官网下载一个,这里使用的是Win64_1.1版本。打开Powershell或者CMD,输入以下命令:

cmd>openssl req -newkey rsa:2048 -nodes -keyout cas.clientservice.key -x509 -days 365 -out cas.clientservice.cer
下面将生成的证书和Key封装成一个文件,以便IdentityServer可以使用它们去正确地签名tokens
cmd>openssl pkcs12 -export -in cas.clientservice.cer -inkey cas.clientservice.key -out cas.clientservice.pfx

最后生成如下:

 

 这里我将其放到了项目结构文件夹中,并设置这个pfx文件为“如果较新则复制”,确保可以在最后生成的目录里边。现在就可以修改一下ConfigureServices()方法了:
  

 public void ConfigureServices(IServiceCollection services)
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        InMemoryConfiguration.Configuration = this.Configuration;

        services.AddIdentityServer()
            //.AddDeveloperSigningCredential()
            .AddSigningCredential(new X509Certificate2(Path.Combine(basePath,
                Configuration["Certificates:CerPath"]),
                Configuration["Certificates:Password"]))
          .AddTestUsers(InMemoryConfiguration.GetUsers().ToList())
          .AddInMemoryClients(InMemoryConfiguration.GetClients())
        .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources());
    }

这里我将证书的路径和导出密码都写到了配置文件中:

{
  "Certificates": {
    "CerPath": "certificate\\cas.clientservice.pfx",
    "Password": "manulife"
  }
} 

也可以查看eShopOnContainers解决方案下Identity.API的配置

 

参考文章 

OpenSSL下载

我的OpenSSL文章

 

posted on 2022-12-26 16:03  花阴偷移  阅读(45)  评论(0编辑  收藏  举报

导航