IdentityServer4:无法加载证书,无法加载证书

时间:2017-09-03 12:31:55

标签: c# asp.net-mvc identityserver4 asp.net-core-2.0

我无法加载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

2 个答案:

答案 0 :(得分:1)

我正在使用以下代码行

从Startup.cs加载证书
X509Certificate2 cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "cetname.pfx"), "password");

答案 1 :(得分:1)

您需要将.pfx文件上的Build Action更改为EmbeddedResource。在文件的属性窗口中可以轻松地在Visual Studio中完成。

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