#X509 clientauthentication
Explore tagged Tumblr posts
manishdhoj-blog · 8 years ago
Text
Client certificate Authentication
Lately I had to implement a feature in one of my application where I had to authenticate a client before making an API call. Below are the steps I followed to implement it in .NET.
1. Getting the SSL certificate
First step is to obtain the client SSL certificate. This can be obtained from the CA or from the party who authenticates the client if he/she has it. When a CA creates a certificate it creates two certificate one for the server and the other the client. The client certificate includes 
CA name Validity period Client Name Public key/Private Key Additional Info Digital Signature of CA The client certificate is in X.509 format.
2. Once we have the client certificate we install the certificate. You may be able to install the server by clicking and install.
3. After the certificate is installed, it needs to be retrieved and added to the HttpRequest when making API Call.
If this application is to be deployed, the certificate also needs to be installed into the server where it is to be deployed.
Below is the code snippet how the client authentication is done by passing the client certificate.
var request = WebRequest.Create(apiURL) as HttpWebRequest;            X509Store store = new X509Store("My", StoreLocation.LocalMachine);            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);            X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindBySubjectName, “myCertificateName”, false);            if(cers.Count != 1)                throw new ObjectNotFoundException("SSL certificate "+ certificateName + " not installed in the machine. Please install certificate.");             
           request.Method = "POST";            request.ContentType = "application/json";            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;            request.Headers["username"] = "username”;            request.Headers["password"] = "password”;            request.ClientCertificates.Add(cers[0]);            Byte[] bt = Encoding.UTF8.GetBytes(jsonRequestParameters);            Stream st = request.GetRequestStream();            st.Write(bt, 0, bt.Length);            st.Close();
           using (var response = (HttpWebResponse)request.GetResponse())            {                if (response.StatusCode != HttpStatusCode.OK)                    throw new Exception(                        $"Server error (HTTP {response.StatusCode}: {response.StatusDescription}).");                using (var webResponse = new StreamReader(response.GetResponseStream()))                {                    var myResponse= webResponse.ReadToEnd();                    return myResponse ;                }            }
0 notes