Java – read the incoming Certificate in Tomcat

I use Tomcat HTTP connector to authenticate with clients If the client starts a new connection to my server and sends his certificate, I can get the certificate from my java code and read the common name from the incoming certificate If so, what?

Thank you, ADI

Solution

You can get javax. XML by using HttpServletRequest servlet. request. X509certificate attribute to obtain the client certificate chain This is an x509certificates series, where the first (position 0) is the actual client certificate (if an intermediate CA certificate is required, the rest of the chain may exist)

X509Certificate certs[] = 
    (X509Certificate[])req.getAttribute("javax.servlet.request.X509Certificate");
// ... Test if non-null,non-empty.

X509Certificate clientCert = certs[0];

// Get the Subject DN's X500Principal
X500Principal subjectDN = clientCert.getSubjectX500Principal();

Then, you can obtain various rDNS (relative distinguished names) in the principal (such as CN) described in this answer:

import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;

String dn = subjectDN.getName();
LdapName ldapDN = new LdapName(dn);
for(Rdn rdn: ldapDN.getRdns()) {
    System.out.println(rdn.getType() + " -> " + rdn.getValue());
}

(you can also use the x509name of bouncycastle to get each RDN.)

In the X.509 certificate, the subject DN is an ordered sequence of rDNS, each of which is a set of AVAs (attribute value assertions), such as CN =... Or o = In principle, it can be multiple AVAs per RDN, which will cause problems here, but this is very rare You can almost assume that there is only one AVA per RDN (maybe this answer may be of interest)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>