我正在使用Java 8
中的Apache HTTP client
(版本4.5.13
(执行POST调用,该调用要求客户端使用我存储在.PFX文件中的证书证书进行身份验证。
这是我正在使用的代码:
public static void performClientRequest() throws Exception {
//Trust Strategy to accept any server certificate
TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
};
//Load PFX client certificate
KeyStore clientStore = KeyStore.getInstance("PKCS12");
InputStream instream = new FileInputStream("C:\client.pfx");
try {
clientStore.load(instream, null);
} finally {
instream.close();
}
//Create ssl context with key store and trust strategy
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(clientStore, null)
.loadTrustMaterial(trustStrategy)
.build();
//Create ssl socket factory from context
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
//Create HTTP client
HttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslSocketFactory)
.build();
//Perform call
URI url = new URI("https://mysite.foo");
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type","application/json");
request.setHeader("Accept", "application/json");
String body = "...";
StringEntity bodyEntity = new StringEntity(body);
request.setEntity(bodyEntity);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
}
我过去使用过这个代码,当时它运行得很好,但现在我正在尝试重用它,它只是不发送证书,服务器回复:
HTTP/1.1 403 No client certificate supplied
如何调试并发现证书未发送的原因?
注意:我在C#
和使用Postman
中都实现了类似的调用,在这两种情况下都能很好地工作,所以客户端对服务器的证书身份验证是有效的,只是在我的Java实现中不起作用。
所以,我不知道这是错误还是预期行为(如果是,为什么?(,但显然PFX文件必须有密码保护,才能正确发送。我无法像在问题中发布的代码中那样,使用未受保护的PFX文件并将null
作为密码进行传递。
所以问题解决了,但我很好奇是否有人能评论为什么会发生这种情况。