“X509.LocalMachine.My.SubjectDistinguishedName.Find”始终返回null

问题描述 投票:0回答:1

我们正在.NET Core Web Application中加载IdentityServer4的X509证书,但它始终返回null。使用X509.LocalMachine.My.SubjectDistinguishedName.Find方法时,默认的商店位置是什么?如果我们使用解决方案嵌入源证书,我们如何加载证书?

这是我们的startup.cs文件:

 private static void ConfigureSigningCerts(IServiceCollection services)
    {
        var keys = new List<SecurityKey>();

        var name = "CertName_IdentityServer";

        //The one that expires last at the top
        var certs = X509.LocalMachine.My.SubjectDistinguishedName.Find("CN=" + name, false)
            .Where(o => DateTime.UtcNow >= o.NotBefore)
            .OrderByDescending(o => o.NotAfter);

        if (!certs.Any()) throw new Exception("No valid certificates could be found.");

        //Get first (in desc order of expiry) th
        var signingCert = certs.FirstOrDefault();

        if (signingCert == null) throw new InvalidOperationException("No valid signing certificate could be found.");

        var signingCredential = new SigningCredentials(new X509SecurityKey(signingCert), "RS256");
        services.AddSingleton<ISigningCredentialStore>(new DefaultSigningCredentialsStore(signingCredential));

        foreach (var cert in certs)
        {
            var validationCredential = new SigningCredentials(new X509SecurityKey(cert), "RS256");
            keys.Add(validationCredential.Key);
        }

        services.AddSingleton<IValidationKeysStore>(new DefaultValidationKeysStore(keys));
    }

我们使用以下命令创建自签名证书:

makecert -r -pe -n "CN=CertName_IdentityServer" -b 01/01/2015 -e 01/01/2039 -eku 1.3.6.1.5.5.7.3.3 -sky signature -a sha256 -len 2048 identityserver.cer
asp.net-core .net-core identityserver4
1个回答
1
投票

可以使用byte []或文件路径构造X509Certificate2类,也可以从证书存储区返回。

e.g:

    var assembly = typeof(Startup).GetTypeInfo().Assembly;
    /*
    * IdentityServer\
    *     Certificates\
    *         cert.cer
    * 
    * {assembly name}.{directory}.{file name}
    */
    using (Stream resource = assembly.GetManifestResourceStream("IdentityServer.Certificates.cert.cer"))
    using (var reader = new BinaryReader(resource))
    {
        signingCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(reader.ReadBytes((int)resource.Length));
    }

或者非常相似的东西。

© www.soinside.com 2019 - 2024. All rights reserved.