Search code examples
c#servercertificate

Access server certificate from ASP.NET (C#)


Using server variables(Request.ServerVariables["CERT_SERVER_ISSUER"]), I can get a string representing the Server Certificate Issuer used in the connection.

I would like to access the actual certificate (X509Certificate if possible), so that I can further inspect the certificate.

I want to validate the server certificate in my ASP.NET code, to make sure nobody has simply clicked "..proceed anyway". Specifically I want to check the CA Root.

The way I understand it - typically browsers will not present a client certificate - so:

HttpContext.Current.Request.ClientCertificate

will be null/empty... I'm looking for the Server Certificate, and if possible the full chain of the Server Certificate so I can check the CA Root.


Solution

  • You can obtain certificates from the certificate store, you can do it by subject name, thumbprint, or something else if you want. You'll need to determine which of these you have available - and change the "find type" in this example:

    X509Store store = new X509Store(StoreLocation.LocalMachine);
    store.Open(OpenFlags.ReadOnly);
    
    X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "Subject Name", false);
    if (certs.Count > 0)
    {
        // do something with: certs[0];
    };
    
    store.Close();