IdentityServer4:无法加载证书,加载证书时遇到问题

IdentityServer4: Unable to load certificate, having trouble loading the certificate

我无法加载 x509 证书。

问题:找不到证书。我检查了一下,它就在那里! :(


    public static X509Certificate2 Get()
    {
        var assembly = typeof(Certificate).GetTypeInfo().Assembly;
        var names = assembly.GetManifestResourceNames();

        /***********************************************************************************************
         *  Please note that here we are using a local certificate only for testing purposes. In a 
         *  real environment the certificate should be created and stored in a secure way.
         **********************************************************************************************/
        using (var stream = assembly.GetManifestResourceStream("Identity.API.Certificate.idsrv3test.pfx"))
        {
            return new X509Certificate2(ReadStream(stream), "idsrv3test");
        }
    }

    private static byte[] ReadStream(Stream input)
    {
        byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }

参考https://github.com/dotnet-architecture/eShopOnContainers/blob/38ade408629a606bc63bb09ea1f4e54ca473e617/src/Services/Identity/Identity.API/Certificate/Certificate.cs

我正在使用以下代码行从 Startup.cs 加载证书

X509Certificate2 cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "cetname.pfx"), "password");

您需要将 .pfx 文件上的构建操作更改为 EmbeddedResource。在文件 window 的属性 Visual Studio 中很容易做到。

您可以在 csproj 中看到这样的结果: https://github.com/dotnet-architecture/eShopOnContainers/blob/38ade408629a606bc63bb09ea1f4e54ca473e617/src/Services/Identity/Identity.API/Identity.API.csproj