要将CXF客户端的TLS/SSL Http身份验证用于Web服务,请按照以下步骤操作:
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
// 创建CXF客户端代理
MyService service = new MyService();
MyServicePort port = service.getMyServicePort();
// 设置客户端身份验证信息
Map<String, Object> requestContext = ((BindingProvider) port).getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://example.com/myservice");
requestContext.put(BindingProvider.USERNAME_PROPERTY, "myusername");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
// 调用Web服务
MyResponse response = port.myOperation(new MyRequest());
通过以上步骤,您可以将CXF客户端的TLS/SSL Http身份验证用于Web服务。请注意,这种方法会绕过所有SSL证书验证,因此在生产环境中使用时需要谨慎。
领取专属 10元无门槛券
手把手带您无忧上云