Retrieve client cert in Servlet when using mutual authentication?

醉酒当歌 提交于 2020-01-24 11:27:46

问题


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:


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
}


来源:https://stackoverflow.com/questions/25161886/retrieve-client-cert-in-servlet-when-using-mutual-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!