Retrieve client cert in Servlet when using mutual

2019-07-04 11:35发布

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.

1条回答
Root(大扎)
2楼-- · 2019-07-04 12:00

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=([^,]*)(,|$)");
  cn = p.matcher(dn).find().group(2);
} else {
  // no certificate provided
}
查看更多
登录 后发表回答