Reputation: 151
We are loading the X509 certificates for IdentityServer4 in .NET Core Web Application, but it always returns null. What is the default store location when we use X509.LocalMachine.My.SubjectDistinguishedName.Find
method? How we can load certificate if we embedded source certificates with solution?
Here is our startup.cs file:
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));
}
We have used following command to create self-signed certificate:
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
Upvotes: 0
Views: 396
Reputation: 5264
The X509Certificate2 class can be constructed using a byte[] or file path as well as being returned from the certificate store.
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));
}
Or something very similar.
Upvotes: 1