java中的http调用未发送客户端证书

2mbi3lxu  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(222)

我用的是 Apache HTTP client (版本 4.5.13 )在 Java 8 执行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实现中不工作。

31moq8wy

31moq8wy1#

所以,我不知道这是否是一个错误或预期的行为(如果是这样,为什么?),但显然pfx文件必须密码保护,然后才能正确发送。我不能使这个工作与一个非保护的pfx文件和传递 null 就像我在问题中发布的密码一样。
所以问题解决了,但我很好奇是否有人可以评论为什么会发生这种情况。

相关问题