c# - Reading all certificates from asp.net -
i have problem reading certificates. have web service has certificate serial number using part of subject. works fine if i'm doing form when try web service seems cannot find certificate. i'm using code read of the certificates:
x509store store = new x509store(); store.open(openflags.readonly); if (args.parameters["certificatename"].tostring() != "") { foreach (x509certificate2 mcert in store.certificates) { if (mcert.subject.contains("ou=" + args.parameters["certificatename"].tostring())) { serialnum = mcert.serialnumber; break; } } if (serialnum == string.empty) { throw new exception("certificate not found name: " + args.parameters["certificatename"].tostring() + " ;" + " ou=" + args.parameters["certificatename"]); } } else { foreach (x509certificate2 mcert in store.certificates) { if (mcert.subject.contains("ou=eua")) { serialnum = mcert.serialnumber; break; } } if (serialnum == string.empty) { throw new exception("haven't found default certificate ;"); } } store=null;
you using parameterless constructor x509store according documentation open cert store current user. well, current user forms application not same current user web application, runs within appdomain configured use service account. means web application won't able find it.
to fix this, have 2 options
option 1
first store certificate in machine store (not user store). then, in code, open store using a different constructor lets specify store location, , specify want machine store. this:
var store = new x509store(storelocation.machinestore);
option 2
maintain 2 copies of certificate. follow these steps:
- export certificate current user's cert store
- start certificate manager using "runas" impersonate service account app domain, e.g.
runas /user:mydomain\myserviceaccount "cmd /c start /b certmgr.msc"
. when prompted make sure tell want work current user's cert store, not machine store. - import certificate there
- open cert , make sure chain of trust intact; if intermediate or root certs missing, may have import well.
- remember when cert expires, have replace both copies.
Comments
Post a Comment