Tomcat配置SSL双向认证(2)

1 package com.rorymo.demo.ssl; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.security.cert.X509Certificate; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * 15 * SSLServlet 16 * 17 * @author rorymo 18 * @version 1.0 19 */ 20 @WebServlet("/SSLServlet") 21 public class SSLServlet extends HttpServlet { 22 23 private static final long serialVersionUID = 1601507150278487538L; 24 private static final String REQUEST_ATTR_CERT = "javax.servlet.request.X509Certificate"; 25 private static final String CONTENT_TYPE = "text/plain;charset=UTF-8"; 26 private static final String DEFAULT_ENCODING = "UTF-8"; 27 private static final String SCHEME_HTTPS = "https"; 28 29 public void doGet(HttpServletRequest request, HttpServletResponse response) 30 throws ServletException, IOException { 31 response.setContentType(CONTENT_TYPE); 32 response.setCharacterEncoding(DEFAULT_ENCODING); 33 PrintWriter out = response.getWriter(); 34 X509Certificate[] certs = (X509Certificate[]) request.getAttribute(REQUEST_ATTR_CERT); 35 if (certs != null) { 36 int count = certs.length; 37 out.println("共检测到[" + count + "]个客户端证书"); 38 for (int i = 0; i < count; i++) { 39 X509Certificate cert = certs[i]; 40 out.println("客户端证书 [" + cert.getSubjectDN() + "]: "); 41 out.println("证书是否有效:" + (verifyCertificate(cert) ? "是" : "否")); 42 out.println("证书详细信息:\r" + cert.toString()); 43 } 44 } else { 45 if (SCHEME_HTTPS.equalsIgnoreCase(request.getScheme())) { 46 out.println("这是一个HTTPS请求,但是没有可用的客户端证书"); 47 } else { 48 out.println("这不是一个HTTPS请求,因此无法获得客户端证书列表 "); 49 } 50 } 51 out.close(); 52 } 53 54 public void doPost(HttpServletRequest request, HttpServletResponse response) 55 throws ServletException, IOException { 56 doGet(request, response); 57 } 58 59 /** 60 * 61 * 校验证书是否过期 62 * 63 * 64 * @param certificate 65 * @return 66 */ 67 private boolean verifyCertificate(X509Certificate certificate) { 68 boolean valid = true; 69 try { 70 certificate.checkValidity(); 71 } catch (Exception e) { 72 e.printStackTrace(); 73 valid = false; 74 } 75 return valid; 76 } 77 78

4. 在web应用的web.xml中加入如下配置

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/6af336cb05cd865288c47546bfd3ebba.html