使用双向身份验证时在Servlet中检索客户端证书? [英] Retrieve client cert in Servlet when using mutual authentication?

查看:143
本文介绍了使用双向身份验证时在Servlet中检索客户端证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java和Tomcat 7.0构建Web应用程序.

I am building a web application using Java and Tomcat 7.0.

我在服务器端有一个自签名证书(以后我将获得一个正式的证书),并且我已将客户端的根证书添加到其信任库中.我已经在server.xml文件中的以下行上为端口3443上的https协议设置了必需的双向身份验证:

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.

我现在想知道如何在Servlet上获取该使用过的证书的属性以根据用户的证书登录.在这种情况下使用的所有证书将具有不同的CN,因此我想使用该证书来标识用户.

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.

推荐答案

您将需要导入java.security.cert.X509Certificate和.在您的doGet(...)方法中,使用以下命令:

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
}

这篇关于使用双向身份验证时在Servlet中检索客户端证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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