Get Client Certificate

Description :


The following code is used to get the Client Certificate

Name spaces used

using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;


Code Segment

class MainClass {
public static void Main() {

WebRequest MyWebRequestA = WebRequest.Create("http://www.Mysite.com");
MyWebRequestA.Credentials = new NetworkCredential("userName", "password");
MyWebRequestA.PreAuthenticate = true;
WebRequest MyWebRequestB = WebRequest.Create("http://www.Mysite.com");
MyWebRequestB.Credentials = CredentialCache.DefaultCredentials;
MyWebRequestB.PreAuthenticate = true;

HttpWebRequest requestC = (HttpWebRequest)WebRequest.Create("http://www.Mysite.com");
X509Certificate cert1 = X509Certificate.CreateFromCertFile("TestCertificate.cer");
requestC.ClientCertificates.Add(cert1);
HttpWebRequest requestD = (HttpWebRequest)WebRequest.Create("http://www.Mysite.com");
X509Store store = new X509Store();
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName,"Joe", false);

if (certs.Count == 1) {
requestD.ClientCertificates.Add(certs[0]);
} else {
certs = X509Certificate2UI.SelectFromCollection(
store.Certificates,
"Select Certificate",
"Select the certificate to use for authentication.",
X509SelectionFlag.SingleSelection);

if (certs.Count != 0) {
requestD.ClientCertificates.Add(certs[0]);
}
}
}
}



By
Nathan


Comments

Author: Vinay Singh31 Aug 2010 Member Level: Gold   Points : 1

Hi,
I am getting the below error while running your code. How I can resolve this


Error 1 The name 'X509Certificate2UI' does not exist in the current context D:\Data\Websites\TestWMW\GUI\Cert\GetCert.aspx.cs 43 21 D:\...\GUI\


Author: Pal (Parthiv) Patel31 Aug 2010 Member Level: Gold   Points : 1

-----------1111111111-------------------
hey nathan
this one is awesome code snippet
keep it up
put good codes and earn money and points
------------!!!!!!!!!!-------------------



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: