Java Code Examples for org.apache.cxf.transport.http.HTTPConduit#setTlsClientParameters()

The following examples show how to use org.apache.cxf.transport.http.HTTPConduit#setTlsClientParameters() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static WebClient createTrustedWebClient( String url, Object provider )
{
    WebClient client = WebClient.create( url, Arrays.asList( provider ) );

    HTTPConduit httpConduit = ( HTTPConduit ) WebClient.getConfig( client ).getConduit();

    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout( defaultConnectionTimeout );
    httpClientPolicy.setReceiveTimeout( defaultReceiveTimeout );
    httpClientPolicy.setMaxRetransmits( defaultMaxRetransmits );


    httpConduit.setClient( httpClientPolicy );

    SSLManager sslManager = new SSLManager( null, null, null, null );

    TLSClientParameters tlsClientParameters = new TLSClientParameters();
    tlsClientParameters.setDisableCNCheck( true );
    tlsClientParameters.setTrustManagers( sslManager.getClientFullTrustManagers() );
    httpConduit.setTlsClientParameters( tlsClientParameters );

    return client;
}
 
Example 2
Source File: SSLNettyServerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void setupTLS(Greeter port)
    throws FileNotFoundException, IOException, GeneralSecurityException {
    String keyStoreLoc =
        "/keys/clientstore.jks";
    HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(port).getConduit();

    TLSClientParameters tlsCP = new TLSClientParameters();
    String keyPassword = "ckpass";
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(SSLNettyServerTest.class.getResourceAsStream(keyStoreLoc), "cspass".toCharArray());
    KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
    tlsCP.setKeyManagers(myKeyManagers);


    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(SSLNettyServerTest.class.getResourceAsStream(keyStoreLoc), "cspass".toCharArray());
    TrustManager[] myTrustStoreKeyManagers = getTrustManagers(trustStore);
    tlsCP.setTrustManagers(myTrustStoreKeyManagers);

    tlsCP.setDisableCNCheck(true);
    httpConduit.setTlsClientParameters(tlsCP);
}
 
Example 3
Source File: SoapClient.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Configures the SSL environment.
 */
protected void configureSSL() {
	TLSClientParameters tlsParams = new TLSClientParameters();
	tlsParams.setDisableCNCheck(true);
	tlsParams.setTrustManagers(new TrustManager[] { new EasyX509TrustManager() });

	org.apache.cxf.endpoint.Client cl = ClientProxy.getClient(client);
	HTTPConduit httpConduit = (HTTPConduit) cl.getConduit();
	httpConduit.setTlsClientParameters(tlsParams);
}
 
Example 4
Source File: CalculatorTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static void setupTLS(final Object port) throws GeneralSecurityException, IOException {

        final HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(port).getConduit();

        final TLSClientParameters tlsCP = new TLSClientParameters();
        final String storePassword = "keystorePass";
        final String keyPassword = "clientPassword";
        final KeyStore keyStore = KeyStore.getInstance("jks");
        final String keyStoreLoc = "META-INF/clientStore.jks";
        keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreLoc), storePassword.toCharArray());

        // set the key managers from the Java KeyStore we just loaded
        final KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
        tlsCP.setKeyManagers(myKeyManagers);
        tlsCP.setCertAlias("clientalias"); // in case there is multiple certs in the keystore, make sure we pick the one we want

        // Create a trust manager that does not validate certificate chains
        // this should not be done in production. It's recommended to create a cacerts with the certificate chain or
        // to rely on a well known CA such as Verisign which is already available in the JVM
        TrustManager[] trustAllCerts = getTrustManagers();
        tlsCP.setTrustManagers(trustAllCerts);

        // don't check the host name of the certificate to match the server (running locally)
        // this should not be done on a real production system
        tlsCP.setHostnameVerifier((s, sslSession) -> true);

        httpConduit.setTlsClientParameters(tlsCP);
    }
 
Example 5
Source File: TrustManagerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNoOpX509TrustManager() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = TrustManagerTest.class.getResource("client-trust.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL url = SOAPService.WSDL_LOCATION;
    SOAPService service = new SOAPService(url, SOAPService.SERVICE);
    assertNotNull("Service is null", service);
    final Greeter port = service.getHttpsPort();
    assertNotNull("Port is null", port);

    updateAddressPort(port, PORT);

    // Enable Async
    if (async) {
        ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true);
    }

    TLSClientParameters tlsParams = new TLSClientParameters();
    tlsParams.setTrustManagers(InsecureTrustManager.getNoOpX509TrustManagers());
    tlsParams.setDisableCNCheck(true);

    Client client = ClientProxy.getClient(port);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setTlsClientParameters(tlsParams);

    assertEquals(port.greetMe("Kitty"), "Hello Kitty");

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 6
Source File: CipherSuitesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAESIncludedTLSv10() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = CipherSuitesTest.class.getResource("ciphersuites-client-noconfig.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL url = SOAPService.WSDL_LOCATION;
    SOAPService service = new SOAPService(url, SOAPService.SERVICE);
    assertNotNull("Service is null", service);
    final Greeter port = service.getHttpsPort();
    assertNotNull("Port is null", port);

    updateAddressPort(port, PORT);

    // Enable Async
    if (async) {
        ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true);
    }

    Client client = ClientProxy.getClient(port);
    HTTPConduit conduit = (HTTPConduit) client.getConduit();

    TLSClientParameters tlsParams = new TLSClientParameters();
    TrustManager[] trustManagers = InsecureTrustManager.getNoOpX509TrustManagers();
    tlsParams.setTrustManagers(trustManagers);
    tlsParams.setDisableCNCheck(true);

    tlsParams.setSecureSocketProtocol("TLSv1");

    conduit.setTlsClientParameters(tlsParams);

    assertEquals(port.greetMe("Kitty"), "Hello Kitty");

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 7
Source File: AmbariClientBuilder.java    From components with Apache License 2.0 5 votes vote down vote up
/**
 * Build a client proxy, for a specific proxy type.
 * 
 * @param proxyType proxy type class
 * @return client proxy stub
 */
protected <T> T build(Class<T> proxyType) {
    String address = generateAddress();
    T rootResource;
    // Synchronized on the class to correlate with the scope of clientStaticResources
    // We want to ensure that the shared bean isn't set concurrently in multiple callers
    synchronized (AmbariClientBuilder.class) {
        JAXRSClientFactoryBean bean = cleanFactory(clientStaticResources.getUnchecked(proxyType));
        bean.setAddress(address);
        if (username != null) {
            bean.setUsername(username);
            bean.setPassword(password);
        }

        if (enableLogging) {
            bean.setFeatures(Arrays.<AbstractFeature> asList(new LoggingFeature()));
        }
        rootResource = bean.create(proxyType);
    }

    boolean isTlsEnabled = address.startsWith("https://");
    ClientConfiguration config = WebClient.getConfig(rootResource);
    HTTPConduit conduit = (HTTPConduit) config.getConduit();
    if (isTlsEnabled) {
        TLSClientParameters tlsParams = new TLSClientParameters();
        if (!validateCerts) {
            tlsParams.setTrustManagers(new TrustManager[] { new AcceptAllTrustManager() });
        } else if (trustManagers != null) {
            tlsParams.setTrustManagers(trustManagers);
        }
        tlsParams.setDisableCNCheck(!validateCn);
        conduit.setTlsClientParameters(tlsParams);
    }

    HTTPClientPolicy policy = conduit.getClient();
    policy.setConnectionTimeout(connectionTimeoutUnits.toMillis(connectionTimeout));
    policy.setReceiveTimeout(receiveTimeoutUnits.toMillis(receiveTimeout));
    return rootResource;
}
 
Example 8
Source File: SyncopeClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance of the given service class, with configured content type and authentication.
 *
 * @param <T> any service class
 * @param serviceClass service class reference
 * @return service instance of the given reference class
 */
public <T> T getService(final Class<T> serviceClass) {
    synchronized (restClientFactory) {
        restClientFactory.setServiceClass(serviceClass);
        T serviceInstance = restClientFactory.create(serviceClass);

        Client client = WebClient.client(serviceInstance);
        client.type(mediaType).accept(mediaType);
        if (serviceInstance instanceof AnyService || serviceInstance instanceof ExecutableService) {
            client.accept(RESTHeaders.MULTIPART_MIXED);
        }

        ClientConfiguration config = WebClient.getConfig(client);
        config.getRequestContext().put(HEADER_SPLIT_PROPERTY, true);
        config.getRequestContext().put(URLConnectionHTTPConduit.HTTPURL_CONNECTION_METHOD_REFLECTION, true);
        if (useCompression) {
            config.getInInterceptors().add(new GZIPInInterceptor());
            config.getOutInterceptors().add(new GZIPOutInterceptor());
        }
        if (tlsClientParameters != null) {
            HTTPConduit httpConduit = (HTTPConduit) config.getConduit();
            httpConduit.setTlsClientParameters(tlsClientParameters);
        }

        return serviceInstance;
    }
}
 
Example 9
Source File: CipherSuitesTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testAESIncludedTLSv11() throws Exception {
    // Doesn't work with IBM JDK
    if ("IBM Corporation".equals(System.getProperty("java.vendor"))) {
        return;
    }

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = CipherSuitesTest.class.getResource("ciphersuites-client-noconfig.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL url = SOAPService.WSDL_LOCATION;
    SOAPService service = new SOAPService(url, SOAPService.SERVICE);
    assertNotNull("Service is null", service);
    final Greeter port = service.getHttpsPort();
    assertNotNull("Port is null", port);

    updateAddressPort(port, PORT);

    // Enable Async
    if (async) {
        ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true);
    }

    Client client = ClientProxy.getClient(port);
    HTTPConduit conduit = (HTTPConduit) client.getConduit();

    TLSClientParameters tlsParams = new TLSClientParameters();
    TrustManager[] trustManagers = InsecureTrustManager.getNoOpX509TrustManagers();
    tlsParams.setTrustManagers(trustManagers);
    tlsParams.setDisableCNCheck(true);

    tlsParams.setSecureSocketProtocol("TLSv1.1");

    conduit.setTlsClientParameters(tlsParams);

    assertEquals(port.greetMe("Kitty"), "Hello Kitty");

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 10
Source File: UsernameTokenTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testPlaintextWSDLOverHTTPSViaCode() throws Exception {

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    final KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", UsernameTokenTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }
    tmf.init(ts);

    TLSClientParameters tlsParams = new TLSClientParameters();
    tlsParams.setTrustManagers(tmf.getTrustManagers());
    tlsParams.setDisableCNCheck(true);

    HTTPConduitConfigurer myHttpConduitConfig = new HTTPConduitConfigurer() {
        public void configure(String name, String address, HTTPConduit c) {
            if ("{http://cxf.apache.org}TransportURIResolver.http-conduit".equals(name)) {
                c.setTlsClientParameters(tlsParams);
            }
        }
    };

    BusFactory busFactory = BusFactory.newInstance();
    bus = busFactory.createBus();
    bus.setExtension(myHttpConduitConfig, HTTPConduitConfigurer.class);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = new URL("https://localhost:" + PORT + "/DoubleItUTPlaintext?wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItPlaintextPort");
    DoubleItPortType utPort =
            service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(utPort, test.getPort());

    if (test.isStreaming()) {
        SecurityTestUtil.enableStreaming(utPort);
    }

    ((BindingProvider)utPort).getRequestContext().put(SecurityConstants.USERNAME, "Alice");

    ((BindingProvider)utPort).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER,
                                                      "org.apache.cxf.systest.ws.common.UTPasswordCallback");

    Client client = ClientProxy.getClient(utPort);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setTlsClientParameters(tlsParams);

    assertEquals(50, utPort.doubleIt(25));

    ((java.io.Closeable)utPort).close();
}
 
Example 11
Source File: UsernameTokenTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testPlaintextCodeFirst() throws Exception {

    String address = "https://localhost:" + PORT + "/DoubleItUTPlaintext";
    QName portQName = new QName(NAMESPACE, "DoubleItPlaintextPort");

    WSPolicyFeature policyFeature = new WSPolicyFeature();
    Element policyElement =
        StaxUtils.read(getClass().getResourceAsStream("plaintext-pass-timestamp-policy.xml")).getDocumentElement();
    policyFeature.setPolicyElements(Collections.singletonList(policyElement));

    JaxWsProxyFactoryBean clientFactoryBean = new JaxWsProxyFactoryBean();
    clientFactoryBean.setFeatures(Collections.singletonList(policyFeature));
    clientFactoryBean.setAddress(address);
    clientFactoryBean.setServiceName(SERVICE_QNAME);
    clientFactoryBean.setEndpointName(portQName);
    clientFactoryBean.setServiceClass(DoubleItPortType.class);

    DoubleItPortType port = (DoubleItPortType)clientFactoryBean.create();

    if (test.isStreaming()) {
        SecurityTestUtil.enableStreaming(port);
    }

    ((BindingProvider)port).getRequestContext().put(SecurityConstants.USERNAME, "Alice");

    ((BindingProvider)port).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER,
                                                      "org.apache.cxf.systest.ws.common.UTPasswordCallback");

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    final KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", UsernameTokenTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }
    tmf.init(ts);

    TLSClientParameters tlsParams = new TLSClientParameters();
    tlsParams.setTrustManagers(tmf.getTrustManagers());
    tlsParams.setDisableCNCheck(true);

    Client client = ClientProxy.getClient(port);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setTlsClientParameters(tlsParams);

    assertEquals(50, port.doubleIt(25));

    ((java.io.Closeable)port).close();
}
 
Example 12
Source File: UsernameTokenTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testPlaintextTLSConfigViaCode() throws Exception {

    URL wsdl = UsernameTokenTest.class.getResource("DoubleItUt.wsdl");
    // URL wsdl = new URL("https://localhost:" + PORT + "/DoubleItUTPlaintext?wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItPlaintextPort");
    DoubleItPortType utPort =
            service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(utPort, test.getPort());

    if (test.isStreaming()) {
        SecurityTestUtil.enableStreaming(utPort);
    }

    ((BindingProvider)utPort).getRequestContext().put(SecurityConstants.USERNAME, "Alice");

    ((BindingProvider)utPort).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER,
                                                      "org.apache.cxf.systest.ws.common.UTPasswordCallback");

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    final KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", UsernameTokenTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }
    tmf.init(ts);

    TLSClientParameters tlsParams = new TLSClientParameters();
    tlsParams.setTrustManagers(tmf.getTrustManagers());
    tlsParams.setDisableCNCheck(true);

    Client client = ClientProxy.getClient(utPort);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setTlsClientParameters(tlsParams);

    assertEquals(50, utPort.doubleIt(25));

    ((java.io.Closeable)utPort).close();
}
 
Example 13
Source File: WSSCUnitTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testEndorsingSecureConverationViaCode() throws Exception {

    URL wsdl = WSSCUnitTest.class.getResource("DoubleItWSSC.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItTransportPort");
    DoubleItPortType port =
            service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(port, test.getPort());

    if (test.isStreaming()) {
        SecurityTestUtil.enableStreaming(port);
    }

    // TLS configuration
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    final KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", WSSCUnitTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }
    tmf.init(ts);

    TLSClientParameters tlsParams = new TLSClientParameters();
    tlsParams.setTrustManagers(tmf.getTrustManagers());
    tlsParams.setDisableCNCheck(true);

    Client client = ClientProxy.getClient(port);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setTlsClientParameters(tlsParams);

    // STSClient configuration
    Bus clientBus = BusFactory.newInstance().createBus();
    STSClient stsClient = new STSClient(clientBus);
    stsClient.setTlsClientParameters(tlsParams);

    ((BindingProvider)port).getRequestContext().put("security.sts.client", stsClient);

    assertEquals(50, port.doubleIt(25));

    ((java.io.Closeable)port).close();
}
 
Example 14
Source File: HTTPSConduitTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testHttpsTrust() throws Exception {
    startServer("Bethal");

    URL wsdl = getClass().getResource("greeting.wsdl");
    assertNotNull("WSDL is null", wsdl);

    SOAPService service = new SOAPService(wsdl, serviceName);
    assertNotNull("Service is null", service);

    Greeter bethal = service.getPort(bethalQ, Greeter.class);
    assertNotNull("Port is null", bethal);
    updateAddressPort(bethal, getPort("PORT4"));

    // Okay, I'm sick of configuration files.
    // This also tests dynamic configuration of the conduit.
    Client client = ClientProxy.getClient(bethal);
    HTTPConduit http =
        (HTTPConduit) client.getConduit();

    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();

    httpClientPolicy.setAutoRedirect(false);
    // If we set any name, but Edward, Mary, or George,
    // and a password of "password" we will get through
    // Bethal.
    AuthorizationPolicy authPolicy = new AuthorizationPolicy();
    authPolicy.setUserName("Betty");
    authPolicy.setPassword("password");

    http.setClient(httpClientPolicy);
    http.setTlsClientParameters(tlsClientParameters);
    http.setAuthorization(authPolicy);

    // Our expected server should be OU=Bethal
    http.setTrustDecider(new MyHttpsTrustDecider("Bethal"));

    configureProxy(client);
    String answer = bethal.sayHi();
    assertTrue("Unexpected answer: " + answer,
            "Bonjour from Bethal".equals(answer));
    assertProxyRequestCount(0);


    // Nobody will not equal OU=Bethal
    MyHttpsTrustDecider trustDecider =
                             new MyHttpsTrustDecider("Nobody");
    http.setTrustDecider(trustDecider);
    try {
        answer = bethal.sayHi();
        fail("Unexpected answer from Bethal: " + answer);
    } catch (Exception e) {
        //e.printStackTrace();
        //assertTrue("Trust Decider was not called",
        //              0 > trustDecider.wasCalled());
    }
    assertProxyRequestCount(0);
}
 
Example 15
Source File: HTTPSConduitTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * This methods tests a basic https connection to Bethal.
 * It supplies an authorization policy with premetive user/pass
 * to avoid the 401.
 */
@Test
public void testHttpsBasicConnection() throws Exception {
    startServer("Bethal");

    URL wsdl = getClass().getResource("greeting.wsdl");
    assertNotNull("WSDL is null", wsdl);

    SOAPService service = new SOAPService(wsdl, serviceName);
    assertNotNull("Service is null", service);

    Greeter bethal = service.getPort(bethalQ, Greeter.class);
    assertNotNull("Port is null", bethal);
    updateAddressPort(bethal, getPort("PORT4"));

    // Okay, I'm sick of configuration files.
    // This also tests dynamic configuration of the conduit.
    Client client = ClientProxy.getClient(bethal);
    HTTPConduit http =
        (HTTPConduit) client.getConduit();

    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();

    httpClientPolicy.setAutoRedirect(false);
    // If we set any name, but Edward, Mary, or George,
    // and a password of "password" we will get through
    // Bethal.
    AuthorizationPolicy authPolicy = new AuthorizationPolicy();
    authPolicy.setUserName("Betty");
    authPolicy.setPassword("password");

    http.setClient(httpClientPolicy);
    http.setTlsClientParameters(tlsClientParameters);
    http.setAuthorization(authPolicy);

    configureProxy(client);
    String answer = bethal.sayHi();
    assertTrue("Unexpected answer: " + answer,
            "Bonjour from Bethal".equals(answer));
    assertProxyRequestCount(0);
}
 
Example 16
Source File: HttpClient.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public static WebClient createTrustedWebClientWithAuth( String url, KeyStore keyStore, char[] keyStorePassword,
                                                        byte[] serverFingerprint ) throws BazaarManagerException
{
    try
    {
        WebClient client = WebClient.create( url );

        // A client certificate is not provided in SSL context if async connection is used.
        // See details: #311 - Registration failure due to inability to find fingerprint.
        Map<String, Object> requestContext = WebClient.getConfig( client ).getRequestContext();
        requestContext.put( "use.async.http.conduit", Boolean.FALSE );

        HTTPConduit httpConduit = ( HTTPConduit ) WebClient.getConfig( client ).getConduit();

        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();

        httpClientPolicy.setConnectionTimeout( SECONDS_30 );

        httpClientPolicy.setReceiveTimeout( SECONDS_60 );

        httpClientPolicy.setMaxRetransmits( DEFAULT_MAX_RETRANSMITS );

        httpConduit.setClient( httpClientPolicy );

        KeyManagerFactory keyManagerFactory =
                KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );

        keyManagerFactory.init( keyStore, keyStorePassword );

        TLSClientParameters tlsClientParameters = new TLSClientParameters();

        tlsClientParameters.setDisableCNCheck( true );

        tlsClientParameters
                .setTrustManagers( new TrustManager[] { new FingerprintTrustManager( serverFingerprint ) } );

        tlsClientParameters.setKeyManagers( keyManagerFactory.getKeyManagers() );

        httpConduit.setTlsClientParameters( tlsClientParameters );

        return client;
    }
    catch ( Exception e )
    {
        throw new BazaarManagerException( e );
    }
}
 
Example 17
Source File: TrustManagerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testValidServerCertX509TrustManager2() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = TrustManagerTest.class.getResource("client-trust.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL url = SOAPService.WSDL_LOCATION;
    SOAPService service = new SOAPService(url, SOAPService.SERVICE);
    assertNotNull("Service is null", service);
    final Greeter port = service.getHttpsPort();
    assertNotNull("Port is null", port);

    updateAddressPort(port, PORT3);

    // Enable Async
    if (async) {
        ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true);
    }

    String validPrincipalName = "CN=Bethal,OU=Bethal,O=ApacheTest,L=Syracuse,C=US";

    TLSClientParameters tlsParams = new TLSClientParameters();
    X509TrustManager trustManager =
        new ServerCertX509TrustManager(validPrincipalName);
    TrustManager[] trustManagers = new TrustManager[1];
    trustManagers[0] = trustManager;
    tlsParams.setTrustManagers(trustManagers);
    tlsParams.setDisableCNCheck(true);

    Client client = ClientProxy.getClient(port);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setTlsClientParameters(tlsParams);

    assertEquals(port.greetMe("Kitty"), "Hello Kitty");

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 18
Source File: WebClientBuilder.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public static WebClient buildEnvironmentWebClient( final PeerInfo peerInfo, final String path,
                                                   final Object provider, long connectTimeoutMs, long readTimeoutMs,
                                                   int maxAttempts )
{
    String effectiveUrl = String.format( ENVIRONMENT_URL_TEMPLATE, peerInfo.getIp(), peerInfo.getPublicSecurePort(),
            path.startsWith( "/" ) ? path : "/" + path );
    WebClient client = WebClient.create( effectiveUrl, Arrays.asList( provider ) );
    client.type( MediaType.APPLICATION_JSON );
    client.accept( MediaType.APPLICATION_JSON );
    HTTPConduit httpConduit = ( HTTPConduit ) WebClient.getConfig( client ).getConduit();

    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout( connectTimeoutMs );
    httpClientPolicy.setReceiveTimeout( readTimeoutMs );
    httpClientPolicy.setMaxRetransmits( maxAttempts );

    httpConduit.setClient( httpClientPolicy );

    KeyStoreTool keyStoreManager = new KeyStoreTool();
    KeyStoreData keyStoreData = new KeyStoreData();
    keyStoreData.setupKeyStorePx2();
    keyStoreData.setAlias( SecuritySettings.KEYSTORE_PX2_ROOT_ALIAS );
    KeyStore keyStore = keyStoreManager.load( keyStoreData );

    LOG.debug( String.format( "Getting key with alias: %s for url: %s", SecuritySettings.KEYSTORE_PX2_ROOT_ALIAS,
            effectiveUrl ) );

    KeyStoreData trustStoreData = new KeyStoreData();
    trustStoreData.setupTrustStorePx2();
    KeyStore trustStore = keyStoreManager.load( trustStoreData );

    SSLManager sslManager = new SSLManager( keyStore, keyStoreData, trustStore, trustStoreData );

    TLSClientParameters tlsClientParameters = new TLSClientParameters();
    tlsClientParameters.setDisableCNCheck( true );
    tlsClientParameters.setTrustManagers( sslManager.getClientTrustManagers() );
    tlsClientParameters.setKeyManagers( sslManager.getClientKeyManagers() );
    tlsClientParameters.setCertAlias( SecuritySettings.KEYSTORE_PX2_ROOT_ALIAS );
    httpConduit.setTlsClientParameters( tlsClientParameters );
    return client;
}
 
Example 19
Source File: TrustManagerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testOSCPOverride() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = TrustManagerTest.class.getResource("client-trust.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL url = SOAPService.WSDL_LOCATION;
    SOAPService service = new SOAPService(url, SOAPService.SERVICE);
    assertNotNull("Service is null", service);
    final Greeter port = service.getHttpsPort();
    assertNotNull("Port is null", port);

    updateAddressPort(port, PORT2);

    // Enable Async
    if (async) {
        ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true);
    }

    // Read truststore
    KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/cxfca.jks", TrustManagerTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }

    try {
        Security.setProperty("ocsp.enable", "true");

        PKIXBuilderParameters param = new PKIXBuilderParameters(ts, new X509CertSelector());
        param.setRevocationEnabled(true);

        TrustManagerFactory tmf  =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(new CertPathTrustManagerParameters(param));

        TLSClientParameters tlsParams = new TLSClientParameters();
        tlsParams.setTrustManagers(tmf.getTrustManagers());
        tlsParams.setDisableCNCheck(true);

        Client client = ClientProxy.getClient(port);
        HTTPConduit http = (HTTPConduit) client.getConduit();
        http.setTlsClientParameters(tlsParams);

        try {
            port.greetMe("Kitty");
            fail("Failure expected on an invalid OCSP responder URL");
        } catch (Exception ex) {
            // expected
        }

    } finally {
        Security.setProperty("ocsp.enable", "false");
    }

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 20
Source File: ClientAuthTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testDirectTrustUsingKeyManagers() throws Exception {

    URL url = SOAPService.WSDL_LOCATION;
    SOAPService service = new SOAPService(url, SOAPService.SERVICE);
    assertNotNull("Service is null", service);
    final Greeter port = service.getHttpsPort();
    assertNotNull("Port is null", port);

    updateAddressPort(port, PORT);

    // Enable Async
    if (async) {
        ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true);
    }

    // Set up KeyManagers/TrustManagers
    KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", ClientAuthTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);

    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream keyStore =
        ClassLoaderUtils.getResourceAsStream("keys/Morpit.jks", ClientAuthTest.class)) {
        ks.load(keyStore, "password".toCharArray());
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, "password".toCharArray());

    TLSClientParameters tlsParams = new TLSClientParameters();
    tlsParams.setKeyManagers(kmf.getKeyManagers());
    tlsParams.setTrustManagers(tmf.getTrustManagers());
    tlsParams.setDisableCNCheck(true);

    Client client = ClientProxy.getClient(port);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setTlsClientParameters(tlsParams);

    assertEquals(port.greetMe("Kitty"), "Hello Kitty");

    ((java.io.Closeable)port).close();
}