问题
I am impersonating a service user account in order to connect to a webservice that requires a cert to connect. I have installed the client cert on the service account on the machine which is running the code however I receive the error System.Security.Cryptography.CryptographicException: The system cannot find the file specified.
using (var ctx = new ImpersonationContext("svcAcctUserName", "domain", "password"))
{
var clientCert = new X509Certificate2("filePath", "certPassword");
}
The impersonation code works, for brevity I have left it out but I check to make sure my context is switched to the svcAcctUserName user by logging the Environment.UserName, which shows that I am running as svcAcctUserName. The filePath is correct, again I left it out, but I open and close the file before I create the X509Certificate2 object to make sure I have both access to the file and that my path is correct.
The error is confusing since I provide the path as a parameter and I know for certain the user running the code has access.
EDIT:
Also tried to do this: How to call a Web service by using a client certificate for authentication in an ASP.NET Web application
Although I am not using an asp.net application, I gave it a try anyway. I added the certificates add-in to the mmc, added the "local computer" certificates add in and then imported the cert into the Personal store of the local machine.
I then ran:
WinHttpCertCfg.exe -g -c LOCAL_MACHINE\My -s issuedToName -a domain\svcAcctUserName
Tried running the operation again, still same problem.
What am I missing?
回答1:
So, as Alex pointed out, I do not understand the underlying architecture of certificate system in windows. However, after performing the above steps and modifying my code to use the X509Store, I have it working. Hopefully this will help someone:
using (var ctx = new ImpersonationContext("svcAcctUserName", "domain", "password"))
{
var store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var clientCert = store.Certificates.Find(X509FindType.FindByIssuerName, "IssuerNameHere", false);
var clientCert2 = new X509Certificate2(clientCert[0]);
}
来源:https://stackoverflow.com/questions/10841627/accessing-impersonated-users-key-store