I work on an IIS6/ASP.NET website that must "require client certificates" in the form of a smart card (specifically a Common Access Card). I need to create a few services to access various URLs on a timer to do things like update search indices, warm up Sharepoint pages, and other tasks.
How can this be done, given that the site doesn't allow access unless you have a certificate, which is on the smartcard? I have tried to load the certificate (.cer) and load it in like this:
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("https://.../someURL.html");
const string certFilename = @"my.cer";
var cert = X509Certificate2.CreateFromCertFile(certFilename);
cert.Import(certFilename, "my pin", X509KeyStorageFlags.Exportable);
request.ClientCertificates.Add(cert);
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
But I get a 403 Forbidden.
You can load your cert from your personal store as follows:
System.Security.Cryptography.X509Certificates.X509Certificate cert = FindCertByName(PART_AFTER_CN_IN_CERT_SUBJECT);
request.ClientCertificates.Add(cert);
..
private System.Security.Cryptography.X509Certificates.X509Certificate FindCertByName(string simpleName)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate cert in store.Certificates)
{
if( cert.Subject.Contains("CN="+simpleName))
{
return cert;
}
}
string msg = "The '" + simpleName + "' security certificate is not installed on this system!";
throw new ApplicationException(msg);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With