我已经编写了启用 SSL 的 Spring Boot Rest 服务。我想在调用服务时从http请求中提取客户端证书的公钥。
我正在尝试
httpServletRequest.getAttribute("javax.servlet.request.X509Certificate");
这给出了 null。
如果我尝试
httpServletRequest.getAttribute("javax.servlet.request.ssl_session_mgr");
它在 JSSESupport objcet 中为我提供了 SSLSession,其中包含本地证书,但它是私有的,我无法提取证书。
下面是我的 SSL 配置(application.properties):
server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS
下面是客户端代码,我编写用于将证书发送到我的应用程序:
public void testSeervice(){
char[] passphrase = "changeit".toCharArray(); //password
KeyStore keystore = KeyStore.getInstance("JKS");
//KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream("D:\\Projects\\certvalidator\\src\\main\\resources\\ssl-server.jks"), passphrase); //path
//TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); //instance
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = tmf.getTrustManagers();
context.init(null, trustManagers, null);
SSLSocketFactory sf = context.getSocketFactory();
URL url = new URL("https://localhost:8443/validate");
HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection();
httpsCon.setSSLSocketFactory(sf);
httpsCon.setRequestMethod("GET");
System.out.println("Response Message is " + httpsCon.getResponseMessage());
}
我知道它不能回答问题,但是,对于每个到达这里的人(像我一样):
使用
检索客户端证书时获取 nullgetAttribute("javax.servlet.request.X509Certificate")
请务必像这样在 ServletRequest 上调用 getAttribute:
getAttribute("jakarta.servlet.request.X509Certificate")
属性名称已更改,以与新的 servlet API 保持一致,请参阅 Jakarta Servlet 规范,版本 5.0