Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automate access to an IIS website that has "require client certificates"?

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.

like image 456
Scott Stafford Avatar asked Jan 20 '26 08:01

Scott Stafford


1 Answers

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);
        }
like image 91
PerlDev Avatar answered Jan 21 '26 20:01

PerlDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!