在Tomcat中读取传入证书 [英] Read out incoming certificate in Tomcat

查看:373
本文介绍了在Tomcat中读取传入证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有客户端身份验证的tomcat http连接器。如果客户端开始一个新的连接到我的服务器并发送他的证书,我可以获得证书,并从我的java代码输入证书中读取公用名。如果是,如何?

i use a tomcat http connector with client-authentification. If a client start a new connection to my server and sends his certificate, can i get the certificate and read the common name from the incoming certificate out in my java code. If yes, how?

感谢
adi

thanks adi

推荐答案

您可以通过获取 HttpServletRequest 上的 javax.servlet.request.X509Certificate 属性来获取客户端证书链。这是一组 X509Certificate s ,其中第一个(位置0)是实际的客户端证书(如果需要中间CA证书,则链的其余部分可能存在)。

You can get the client certificate chain by getting the javax.servlet.request.X509Certificate attribute on your HttpServletRequest. This is an array of X509Certificates where the first one (position 0) is the actual client certificate (the rest of the chain may be present if intermediate CA certificates are required).

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();

然后,您可以获得此主体(如CN)中的各种RDN在此回答中:

You can then get the various RDNs (relative distinguished name) in this principal (e.g. CN) as 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());
}

(您也可以使用BouncyCastle的 X509Name 获得每个RDN。)

(You could also use BouncyCastle's X509Name to get each RDN.)

在X.509证书中,主题DN是RDN的有序序列,每个RDN是一组AVA (属性值断言),例如 CN = ... O = ... 。原则上,每个RDN可以有多个AVA,这将导致问题,但这是非常罕见的。你几乎可以假设每个RDN只有一个AVA。 (也许此答案可能会引起您的兴趣。)

In an X.509 certificate, the Subject DN is an ordered sequence of RDNs, each of which is a set of AVAs (Attribute Value Assertions), for example CN=... or O=.... In principle, there can be multiple AVAs per RDN, which would cause problems here, but this is very rare. You can almost assume that there is only one AVA per RDN. (Perhaps this answer might be of interest.)

这篇关于在Tomcat中读取传入证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆