I am building a web application using Java and Tomcat 7.0.
I have a self-signed certificate (in the future I'll get an official one) on the server side, and I've added a client's root certificate to its truststore. I've already set a required two-way authentication for https protocol on port 3443 with the following lines on the server.xml file:
<Connector port="3443" scheme="https" secure="true" SSLEnabled="true" 
        truststoreFile="server.keystore" truststorePass="keystore password" 
        keystoreFile="server.keystore" keystorePass="keystore password" 
        clientAuth="true" keyAlias="serverkey" 
        sslProtocol="TLS"/>
This is working and I can only access the system with a valid certificate.
I was now wondering how I can get a property of this used certificate on my Servlet to log the user in based on his certificate. All certificates used in this context will have a different CN so I want to use that to identify the user.
You will need to import java.security.cert.X509Certificate and . In your doGet(...) method, use the following:
String cn = null;
X509Certificate[] certs = (X509Certificate[]) req
    .getAttribute("javax.servlet.request.X509Certificate");
if (certs != null) {
  String dn = certs[0].getSubjectX500Principal().getName();
  // parse the CN out from the DN (distinguished name)
  Pattern p = Pattern.compile("(^|,)CN=([^,]*)(,|$)");
  Matcher matcher = p.matcher(dn);
  if(matcher.find()) {
    cn = matcher.group(2);
  }
} else {
  // no certificate provided
}
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