相互客户端身份验证在Servlet中获取证书

时间:2012-04-21 22:11:49

标签: java ssl tomcat6

我已经设置了一个Tomcat 7.0应用服务器,它通过SSL进行相互(客户端/服务器)身份验证。要设置此配置,我需要在我的Web浏览器中为服务器和.pks证书创建.jks文件。在Tomcat中配置server.xml文件后,我有相互身份验证和SSL工作。现在我试图在servlet中获取证书,但是我似乎无法从servlet中的请求中获取证书。我可以设置一个成功从请求中提取证书的过滤器。任何人都可以为我提供一个配置/代码,允许我从servlet中获取证书吗?我也接受了为什么我无法在servlet中获取证书的原因。

的Server.xml

<Connector
 clientAuth="true" port="8443" protocol="HTTP/1.1" SSLEnabled="true"
 scheme="https" secure="true"
 keystoreFile="C:/Users/Kevin Bowersox/Desktop/Development/My Certs/server.jks"
 keystoreType="JKS" keystorePass="notmypassword"
 truststoreFile="C:/Users/Kevin Bowersox/Desktop/Development/My Certs/server.jks"
 truststoreType="JKS" truststorePass="notmypassword"
 SSLVerifyClient="require" SSLVerifyDepth="2" sslProtocol="TLS"
/>

MyServlet.java - 这会抛出RuntimeException,因为在点击url时找不到证书:https://localhost:8443/Sample_Application/MyServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
            if (null != certs && certs.length > 0) {
                System.out.println("cert found");
            }
            throw new RuntimeException("No X.509 client certificate found in request");
    }

MyServlet Mapping

<servlet>
    <description>
    </description>
    <display-name>MyServlet</display-name>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

MyFilter.java - 点击url时返回“cert found”:https://localhost:8443/Sample_Application/test.jsp

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
     X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
        if (null != certs && certs.length > 0) {
            System.out.println("cert found");
        }
        //throw new RuntimeException("No X.509 client certificate found in request");
    chain.doFilter(request, response);
}

我的过滤器映射

<filter>
    <description>
    </description>
    <display-name>MyFilter</display-name>
    <filter-name>MyFilter</filter-name>
    <filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
</filter-mapping>

1 个答案:

答案 0 :(得分:7)

它正在发挥作用。但是,Servlet被编码为始终抛出RuntimeException,因此看起来它不起作用。