Search in sources :

Example 76 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project openhab1-addons by openhab.

the class Tr064Comm method createTr064HttpClient.

/***
     * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
     * and sets Auth. Scheme to Digest Auth
     *
     * @param fboxUrl the URL from config file of fbox to connect to
     * @return the ready-to-use httpclient for tr064 requests
     */
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);
    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
    // auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    // known from fbox specification
    digestAuth.overrideParamter("realm", "HTTPS Access");
    // never known at first request
    digestAuth.overrideParamter("nonce", "");
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);
    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        // accept self signed certs
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        // dont
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
    // verify
    // hostname
    // against
    // cert
    // CN
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
    // BUILDER
    // setup builder with parameters defined before
    hc = // set the SSL options which trust every self signed
    HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
    credp).setDefaultRequestConfig(// set the request config specifying timeout
    rc).build();
    return hc;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URISyntaxException(java.net.URISyntaxException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 77 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project openhab1-addons by openhab.

the class IhcConnectionPool method init.

private void init() {
    // Create a local instance of cookie store
    cookieStore = new BasicCookieStore();
    // Create local HTTP context
    localContext = HttpClientContext.create();
    // Bind custom cookie store to the local context
    localContext.setCookieStore(cookieStore);
    httpClientBuilder = HttpClientBuilder.create();
    // Setup a Trust Strategy that allows all certificates.
    logger.debug("Initialize SSL context");
    // Create a trust manager that does not validate certificate chains,
    // but accept all.
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            logger.trace("Trusting server cert: " + certs[0].getIssuerDN());
        }
    } };
    try {
        // Controller supports only SSLv3 and TLSv1
        sslContext = SSLContext.getInstance("TLSv1");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        logger.warn("Exception", e);
    } catch (KeyManagementException e) {
        logger.warn("Exception", e);
    }
    httpClientBuilder.setSslcontext(sslContext);
    // Controller accepts only HTTPS connections and because normally IP
    // address are used on home network rather than DNS names, create custom
    // host name verifier.
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {

        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            logger.trace("HostnameVerifier: arg0 = " + arg0);
            logger.trace("HostnameVerifier: arg1 = " + arg1);
            return true;
        }
    };
    // Create an SSL Socket Factory, to use our weakened "trust strategy"
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build();
    // Create connection-manager using our Registry. Allows multi-threaded
    // use
    PoolingHttpClientConnectionManager connMngr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    // Increase max connection counts
    connMngr.setMaxTotal(20);
    connMngr.setDefaultMaxPerRoute(6);
    httpClientBuilder.setConnectionManager(connMngr);
}
Also used : SSLSession(javax.net.ssl.SSLSession) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 78 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project geode by apache.

the class BaseServiceTest method doLogin.

/**
   * Login to pulse server and setup httpClient for tests To be called from setupBeforeClass in each
   * test class
   */
protected static void doLogin() throws Exception {
    System.out.println("BaseServiceTest ::  Executing doLogin with user : admin, password : admin.");
    CloseableHttpResponse loginResponse = null;
    try {
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpUriRequest login = RequestBuilder.post().setUri(new URI(LOGIN_URL)).addParameter("j_username", "admin").addParameter("j_password", "admin").build();
        loginResponse = httpclient.execute(login);
        try {
            HttpEntity entity = loginResponse.getEntity();
            EntityUtils.consume(entity);
            System.out.println("BaseServiceTest :: HTTP request status : " + loginResponse.getStatusLine());
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                }
            }
        } finally {
            if (loginResponse != null)
                loginResponse.close();
        }
    } catch (Exception failed) {
        logException(failed);
        throw failed;
    }
    System.out.println("BaseServiceTest ::  Executed doLogin");
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) Cookie(org.apache.http.cookie.Cookie) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpEntity(org.apache.http.HttpEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) URI(java.net.URI)

Example 79 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore 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);
        ClientExecutor clientExecutor = new ApacheHttpClient4Executor(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.setRequestSessionState(true);
        AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
        authorizeClient1.setRequest(authorizationRequest1);
        AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);
        //        showClient(authorizeClient1, cookieStore);
        String code1 = authorizationResponse1.getCode();
        String sessionState = authorizationResponse1.getSessionState();
        Assert.assertNotNull("code1 is null", code1);
        Assert.assertNotNull("sessionState is null", sessionState);
        // 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.setSessionState(sessionState);
        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 : ApacheHttpClient4Executor(org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor) ClientExecutor(org.jboss.resteasy.client.ClientExecutor) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.xdi.oxauth.BaseTest)

Example 80 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project ddf by codice.

the class HttpSolrClientFactory method getSecureHttpClient.

private static CloseableHttpClient getSecureHttpClient(boolean retryRequestsOnError) {
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslContext(), getProtocols(), getCipherSuites(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpRequestRetryHandler solrRetryHandler = new SolrHttpRequestRetryHandler();
    HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32);
    if (retryRequestsOnError) {
        builder.setRetryHandler(solrRetryHandler);
    }
    return builder.build();
}
Also used : BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory)

Aggregations

BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)138 HttpResponse (org.apache.http.HttpResponse)54 HttpGet (org.apache.http.client.methods.HttpGet)51 Test (org.junit.Test)44 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)40 RequestConfig (org.apache.http.client.config.RequestConfig)36 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)36 CookieStore (org.apache.http.client.CookieStore)26 Header (org.apache.http.Header)25 HttpClient (org.apache.http.client.HttpClient)25 IOException (java.io.IOException)23 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)22 Cookie (org.apache.http.cookie.Cookie)19 HttpPost (org.apache.http.client.methods.HttpPost)15 CredentialsProvider (org.apache.http.client.CredentialsProvider)14 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)14 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)14 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)13 URI (java.net.URI)12 HttpEntity (org.apache.http.HttpEntity)12