Search in sources :

Example 1 with ApacheHttpClient43Engine

use of org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine in project openremote by openremote.

the class ExtensibleResteasyClientBuilder method initDefaultEngine43.

// The rest is copy/paste pretty much
public static ApacheHttpClient43Engine initDefaultEngine43(ExtensibleResteasyClientBuilder that) {
    HttpClient httpClient = null;
    HostnameVerifier verifier = null;
    if (that.verifier != null) {
        verifier = new ExtensibleResteasyClientBuilder.VerifierWrapper(that.verifier);
    } else {
        switch(that.policy) {
            case ANY:
                verifier = new NoopHostnameVerifier();
                break;
            case WILDCARD:
                verifier = new DefaultHostnameVerifier();
                break;
            case STRICT:
                verifier = new DefaultHostnameVerifier();
                break;
        }
    }
    try {
        SSLConnectionSocketFactory sslsf = null;
        SSLContext theContext = that.sslContext;
        if (that.disableTrustManager) {
            theContext = SSLContext.getInstance("SSL");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new NoopHostnameVerifier();
            sslsf = new SSLConnectionSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SSLConnectionSocketFactory(theContext, verifier) {

                @Override
                protected void prepareSocket(SSLSocket socket) throws IOException {
                    that.prepareSocketForSni(socket);
                }
            };
        } else if (that.clientKeyStore != null || that.truststore != null) {
            SSLContext ctx = SSLContexts.custom().useProtocol(SSLConnectionSocketFactory.TLS).setSecureRandom(null).loadKeyMaterial(that.clientKeyStore, that.clientPrivateKeyPassword != null ? that.clientPrivateKeyPassword.toCharArray() : null).loadTrustMaterial(that.truststore, TrustSelfSignedStrategy.INSTANCE).build();
            sslsf = new SSLConnectionSocketFactory(ctx, verifier) {

                @Override
                protected void prepareSocket(SSLSocket socket) throws IOException {
                    that.prepareSocketForSni(socket);
                }
            };
        } else {
            final SSLContext tlsContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            tlsContext.init(null, null, null);
            sslsf = new SSLConnectionSocketFactory(tlsContext, verifier);
        }
        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
        HttpClientConnectionManager cm = null;
        if (that.connectionPoolSize > 0) {
            PoolingHttpClientConnectionManager tcm = new PoolingHttpClientConnectionManager(registry, null, null, null, that.connectionTTL, that.connectionTTLUnit);
            tcm.setMaxTotal(that.connectionPoolSize);
            if (that.maxPooledPerRoute == 0) {
                that.maxPooledPerRoute = that.connectionPoolSize;
            }
            tcm.setDefaultMaxPerRoute(that.maxPooledPerRoute);
            cm = tcm;
        } else {
            cm = new BasicHttpClientConnectionManager(registry);
        }
        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        if (that.socketTimeout > -1) {
            rcBuilder.setSocketTimeout((int) that.socketTimeoutUnits.toMillis(that.socketTimeout));
        }
        if (that.establishConnectionTimeout > -1) {
            rcBuilder.setConnectTimeout((int) that.establishConnectionTimeoutUnits.toMillis(that.establishConnectionTimeout));
        }
        if (that.connectionCheckoutTimeoutMs > -1) {
            rcBuilder.setConnectionRequestTimeout(that.connectionCheckoutTimeoutMs);
        }
        // The magic configure()
        httpClient = that.configure(HttpClientBuilder.create().setConnectionManager(cm).setDefaultRequestConfig(rcBuilder.build()).setProxy(that.defaultProxy).disableContentCompression()).build();
        ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient, true);
        engine.setResponseBufferSize(that.responseBufferSize);
        engine.setHostnameVerifier(verifier);
        // this may be null.  We can't really support this with Apache Client.
        engine.setSslContext(theContext);
        return engine;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) PassthroughTrustManager(org.jboss.resteasy.client.jaxrs.engines.PassthroughTrustManager) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine) IOException(java.io.IOException) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) HttpClient(org.apache.http.client.HttpClient) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Example 2 with ApacheHttpClient43Engine

use of org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine in project robozonky by RoboZonky.

the class ProxyFactory method newResteasyClient.

public static ResteasyClient newResteasyClient() {
    final ResteasyClientBuilder builder = new ResteasyClientBuilder().readTimeout(Settings.INSTANCE.getSocketTimeout().get(ChronoUnit.SECONDS), TimeUnit.SECONDS).connectTimeout(Settings.INSTANCE.getConnectionTimeout().get(ChronoUnit.SECONDS), TimeUnit.SECONDS);
    /*
         * In order to enable redirects, we need to configure the HTTP Client to support that. Unfortunately, if we then
         * provide such client to the RESTEasy client builder, it will take the client as is and don't do other things
         * that it would have otherwise done to a client that it itself created. Therefore, we do these things
         * ourselves, represented by calling the HTTP engine builder.
         */
    final ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) new ClientHttpEngineBuilder43().resteasyClientBuilder(builder).build();
    engine.setFollowRedirects(true);
    /*
         * Supply the provider factory singleton, as otherwise RESTEasy would create a new instance every time.
         */
    return new ResteasyClientBuilder().providerFactory(ResteasyProviderFactory.getInstance()).httpEngine(engine).build();
}
Also used : ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ClientHttpEngineBuilder43(org.jboss.resteasy.client.jaxrs.ClientHttpEngineBuilder43) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine)

Example 3 with ApacheHttpClient43Engine

use of org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine in project oxAuth by GluuFederation.

the class MTSLClientAuthenticationTest method main.

public static void main(String[] args) throws Exception {
    File jdkJks = new File("u:\\tmp\\ce-ob\\clientkeystore");
    if (!jdkJks.exists()) {
        throw new RuntimeException("Failed to find jks trust store");
    }
    File certificate = new File("u:\\tmp\\ce-ob\\fullchain.p12");
    if (!certificate.exists()) {
        throw new RuntimeException("Failed to find certificate");
    }
    HttpClient httpclient = new DefaultHttpClient();
    // truststore
    KeyStore ts = KeyStore.getInstance("JKS", "SUN");
    ts.load(new FileInputStream(jdkJks), "secret".toCharArray());
    // if you remove me, you've got 'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' on missing truststore
    if (0 == ts.size())
        throw new IOException("Error loading truststore");
    // tmf
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);
    // keystore
    KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE");
    ks.load(new FileInputStream(certificate), "".toCharArray());
    // if you remove me, you've got 'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' on missing keystore
    if (0 == ks.size())
        throw new IOException("Error loading keystore");
    // kmf
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, "".toCharArray());
    // SSL
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    // socket
    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme("https", 443, socketFactory);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    String clientId = "@!D445.22BF.5EF1.0D87!0001!03F2.297D!0008!F599.E2C7";
    String clientSecret = "testClientSecret";
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode("testCode");
    tokenRequest.setRedirectUri("https://ce-ob.gluu.org/cas/login");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.TLS_CLIENT_AUTH);
    TokenClient tokenClient = new TokenClient("https://ce-ob.gluu.org/oxauth/restv1/token");
    tokenClient.setExecutor(new ApacheHttpClient43Engine(httpclient));
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();
    System.out.println(tokenResponse);
    showClient(tokenClient);
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) IOException(java.io.IOException) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) FileInputStream(java.io.FileInputStream) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TokenResponse(org.gluu.oxauth.client.TokenResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) TokenRequest(org.gluu.oxauth.client.TokenRequest) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) File(java.io.File) TokenClient(org.gluu.oxauth.client.TokenClient)

Example 4 with ApacheHttpClient43Engine

use of org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine in project oxAuth by GluuFederation.

the class TestSessionWorkflow method test.

@Parameters({ "userId", "userSecret", "clientId", "clientSecret", "redirectUri" })
@Test
public void test(final String userId, final String userSecret, final String clientId, final String clientSecret, final String redirectUri) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        CookieStore cookieStore = new BasicCookieStore();
        httpClient.setCookieStore(cookieStore);
        ApacheHttpClient43Engine clientExecutor = new ApacheHttpClient43Engine(httpClient);
        // //////////////////////////////////////////////
        // TV side. Code 1                //
        // //////////////////////////////////////////////
        AuthorizationRequest authorizationRequest1 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE), clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);
        authorizationRequest1.setAuthUsername(userId);
        authorizationRequest1.setAuthPassword(userSecret);
        authorizationRequest1.getPrompts().add(Prompt.NONE);
        authorizationRequest1.setState("af0ifjsldkj");
        authorizationRequest1.setRequestSessionId(true);
        AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
        authorizeClient1.setRequest(authorizationRequest1);
        AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);
        // showClient(authorizeClient1, cookieStore);
        String code1 = authorizationResponse1.getCode();
        String sessionId = authorizationResponse1.getSessionId();
        Assert.assertNotNull("code1 is null", code1);
        Assert.assertNotNull("sessionId is null", sessionId);
        // TV sends the code to the Backend
        // We don't use httpClient and cookieStore during this call
        // //////////////////////////////////////////////
        // Backend  1 side. Code 1        //
        // //////////////////////////////////////////////
        // Get the access token
        TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
        TokenResponse tokenResponse1 = tokenClient1.execAuthorizationCode(code1, redirectUri, clientId, clientSecret);
        String accessToken1 = tokenResponse1.getAccessToken();
        Assert.assertNotNull("accessToken1 is null", accessToken1);
        // Get the user's claims
        UserInfoClient userInfoClient1 = new UserInfoClient(userInfoEndpoint);
        UserInfoResponse userInfoResponse1 = userInfoClient1.execUserInfo(accessToken1);
        Assert.assertTrue("userInfoResponse1.getStatus() is not 200", userInfoResponse1.getStatus() == 200);
        // System.out.println(userInfoResponse1.getEntity());
        // //////////////////////////////////////////////
        // TV side. Code 2                //
        // //////////////////////////////////////////////
        AuthorizationRequest authorizationRequest2 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE), clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);
        authorizationRequest2.getPrompts().add(Prompt.NONE);
        authorizationRequest2.setState("af0ifjsldkj");
        authorizationRequest2.setSessionId(sessionId);
        AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint);
        authorizeClient2.setRequest(authorizationRequest2);
        AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor);
        // showClient(authorizeClient2, cookieStore);
        String code2 = authorizationResponse2.getCode();
        Assert.assertNotNull("code2 is null", code2);
        // TV sends the code to the Backend
        // We don't use httpClient and cookieStore during this call
        // //////////////////////////////////////////////
        // Backend  2 side. Code 2        //
        // //////////////////////////////////////////////
        // Get the access token
        TokenClient tokenClient2 = new TokenClient(tokenEndpoint);
        TokenResponse tokenResponse2 = tokenClient2.execAuthorizationCode(code2, redirectUri, clientId, clientSecret);
        String accessToken2 = tokenResponse2.getAccessToken();
        Assert.assertNotNull("accessToken2 is null", accessToken2);
        // Get the user's claims
        UserInfoClient userInfoClient2 = new UserInfoClient(userInfoEndpoint);
        UserInfoResponse userInfoResponse2 = userInfoClient2.execUserInfo(accessToken2);
        Assert.assertTrue("userInfoResponse1.getStatus() is not 200", userInfoResponse2.getStatus() == 200);
    // System.out.println(userInfoResponse2.getEntity());
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
}
Also used : CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AuthorizationRequest(org.gluu.oxauth.client.AuthorizationRequest) TokenResponse(org.gluu.oxauth.client.TokenResponse) UserInfoResponse(org.gluu.oxauth.client.UserInfoResponse) AuthorizeClient(org.gluu.oxauth.client.AuthorizeClient) TokenClient(org.gluu.oxauth.client.TokenClient) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine) UserInfoClient(org.gluu.oxauth.client.UserInfoClient) AuthorizationResponse(org.gluu.oxauth.client.AuthorizationResponse) Parameters(org.testng.annotations.Parameters) BaseTest(org.gluu.oxauth.BaseTest) Test(org.testng.annotations.Test)

Example 5 with ApacheHttpClient43Engine

use of org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine in project oxTrust by GluuFederation.

the class UmaPermissionService method init.

public void init(@Observes @ApplicationInitialized(ApplicationScoped.class) ApplicationInitializedEvent init) {
    try {
        if (this.umaMetadata != null) {
            if (appConfiguration.isRptConnectionPoolUseConnectionPooling()) {
                // For more information about PoolingHttpClientConnectionManager, please see:
                // http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html?org/apache/http/impl/conn/PoolingHttpClientConnectionManager.html
                log.debug("##### Initializing custom ClientExecutor...");
                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
                connectionManager.setMaxTotal(appConfiguration.getRptConnectionPoolMaxTotal());
                connectionManager.setDefaultMaxPerRoute(appConfiguration.getRptConnectionPoolDefaultMaxPerRoute());
                connectionManager.setValidateAfterInactivity(appConfiguration.getRptConnectionPoolValidateAfterInactivity() * 1000);
                CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()).setKeepAliveStrategy(connectionKeepAliveStrategy).setConnectionManager(connectionManager).build();
                ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine(client);
                engine.setFollowRedirects(true);
                this.clientHttpEngine = engine;
                log.info("##### Initializing custom ClientExecutor DONE");
                this.permissionService = UmaClientFactory.instance().createPermissionService(this.umaMetadata, clientHttpEngine);
                this.rptStatusService = UmaClientFactory.instance().createRptStatusService(this.umaMetadata, clientHttpEngine);
            } else {
                this.permissionService = UmaClientFactory.instance().createPermissionService(this.umaMetadata);
                this.rptStatusService = UmaClientFactory.instance().createRptStatusService(this.umaMetadata);
            }
        }
    } catch (Exception ex) {
        log.error("Failed to initialize UmaPermissionService", ex);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine) MalformedURLException(java.net.MalformedURLException) OxIntializationException(org.gluu.exception.OxIntializationException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Aggregations

ApacheHttpClient43Engine (org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine)12 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)4 RequestConfig (org.apache.http.client.config.RequestConfig)3 BaseTest (org.gluu.oxauth.BaseTest)3 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)3 Parameters (org.testng.annotations.Parameters)3 IOException (java.io.IOException)2 HttpClient (org.apache.http.client.HttpClient)2 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)2 AuthorizationRequest (org.gluu.oxauth.client.AuthorizationRequest)2 AuthorizationResponse (org.gluu.oxauth.client.AuthorizationResponse)2 AuthorizeClient (org.gluu.oxauth.client.AuthorizeClient)2 OpenIdConfigurationClient (org.gluu.oxauth.client.OpenIdConfigurationClient)2 OpenIdConfigurationResponse (org.gluu.oxauth.client.OpenIdConfigurationResponse)2 OpenIdConnectDiscoveryClient (org.gluu.oxauth.client.OpenIdConnectDiscoveryClient)2 OpenIdConnectDiscoveryResponse (org.gluu.oxauth.client.OpenIdConnectDiscoveryResponse)2 TokenClient (org.gluu.oxauth.client.TokenClient)2 TokenResponse (org.gluu.oxauth.client.TokenResponse)2 ClientHttpEngine (org.jboss.resteasy.client.jaxrs.ClientHttpEngine)2