使用HttpClient 4.0.1与x509证书进行相互身份验证

hoo*_*knc 12 java authentication httpclient x509

有没有人有关于如何使用HTTPClient 4.0.1通过x509证书执行客户端身份验证的任何友好提示?

感谢您的时间.

laz*_*laz 21

这里有一些代码可以帮助你.该KeyStore是包含客户端证书的对象.如果服务器使用的是自签名证书或未由CA签名的证书,而JVM在包含的cacerts文件中识别,那么您将需要使用TrustStore.否则要使用默认的cacerts文件,请传入nullSSLSockeFactory获取truststore参数.

import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

...

final HttpParams httpParams = new BasicHttpParams();

// load the keystore containing the client certificate - keystore type is probably jks or pkcs12
final KeyStore keystore = KeyStore.getInstance("pkcs12");
InputStream keystoreInput = null;
// TODO get the keystore as an InputStream from somewhere
keystore.load(keystoreInput, "keystorepassword".toCharArray());

// load the trustore, leave it null to rely on cacerts distributed with the JVM - truststore type is probably jks or pkcs12
KeyStore truststore = KeyStore.getInstance("pkcs12");
InputStream truststoreInput = null;
// TODO get the trustore as an InputStream from somewhere
truststore.load(truststoreInput, "truststorepassword".toCharArray());

final SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keystore, keystorePassword, truststore), 443));

final DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
Run Code Online (Sandbox Code Playgroud)

  • 使用jdk 1.6.0_24或更高版本时,不再需要上述注释. (2认同)
  • 对于 Apache HTTP 客户端 4.3+,请参阅 http://stackoverflow.com/a/26159543/340290 (2认同)
  • 对于 Apache HTTP 客户端 4.4+,请参阅 http://stackoverflow.com/a/38313344/340290 (2认同)