Mutual Authentication with x509 Certificates using HttpClient 4.0.1

后端 未结 3 1503
旧时难觅i
旧时难觅i 2020-12-14 03:35

Does anyone have any friendly tips on how to perform client authentication via an x509 certificate using HTTPClient 4.0.1?

3条回答
  •  感动是毒
    2020-12-14 04:13

    Another solution (copied from another example). I've used the same keystore for both 'trusting' (trustStore) and for authenticate myself (keyStore).

     KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
     FileInputStream instream = new FileInputStream(new File("miller.keystore"));
     try {
         trustStore.load(instream, "pw".toCharArray());
     } finally {
         instream.close();
     }
    
     SSLContext sslcontext = SSLContexts.custom()
             .loadTrustMaterial(trustStore) /* this key store must contain the certs needed & trusted to verify the servers cert */
             .loadKeyMaterial(trustStore, "pw".toCharArray()) /* this keystore must contain the key/cert of the client */
             .build();
    
     SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
             SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
     CloseableHttpClient httpclient = HttpClients.custom()
             .setSSLSocketFactory(sslsf)
             .build();
     try {
    
         HttpGet httpget = new HttpGet("https://localhost");
    
         System.out.println("executing request" + httpget.getRequestLine());
    
         CloseableHttpResponse response = httpclient.execute(httpget);
         try {
             HttpEntity entity = response.getEntity();
    
             System.out.println("----------------------------------------");
             System.out.println(response.getStatusLine());
             if (entity != null) {
                 System.out.println("Response content length: " + entity.getContentLength());
             }
             EntityUtils.consume(entity);
         } finally {
             response.close();
         }
     } finally {
         httpclient.close();
     }
    

提交回复
热议问题