I have a problem with an MVC web app which calls to another service using a private certificate.
The certificate is in my Personal keystore against the current machine- I have used winhttpcertcfg
to give permissions to the certificate to the app pool identity of my web application. The key is loaded in the following method;
internal bool SetCertificateFromCertStore(string subjectName)
{
X509Store store = null;
try
{
store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true);
if (certs.Count != 1)
{
store.Close();
store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true);
if (certs.Count != 1)
{
throw new Exception("Unable to find Certificate");
}
}
_certificate = certs[0];
return true;
}
finally
{
if (store != null)
{
store.Close();
}
}
}
This code worked everytime until a couple weeks ago (the 12th of April) when at 17:05 I noticed the first instance in ELMAH of the "Unable to find Certificate" exception being thrown. Checking the applications log, the system is still working on almost all the request with this error cropping up just a few times an hour on some requests.
I've read around similar questions which suggest implementing code similar to the code I'm already using (querying multiple stores). Is there some kind of known issue with the Windows certificate store? Perhaps a locking issue? Is there another way to tackle this or something obvious I'm doing wrong here?
Any help you can offer would be appreciated as I've run out of things to try!