Search in sources :

Example 26 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project crate by crate.

the class BlobHttpIntegrationTest method getRedirectLocations.

public List<String> getRedirectLocations(CloseableHttpClient client, String uri, InetSocketAddress address) throws IOException {
    CloseableHttpResponse response = null;
    try {
        HttpClientContext context = HttpClientContext.create();
        HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s", address.getHostName(), address.getPort(), uri));
        response = client.execute(httpHead, context);
        List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations == null) {
            // client might not follow redirects automatically
            if (response.containsHeader("location")) {
                List<String> redirects = new ArrayList<>(1);
                for (Header location : response.getHeaders("location")) {
                    redirects.add(location.getValue());
                }
                return redirects;
            }
            return Collections.emptyList();
        }
        List<String> redirects = new ArrayList<>(1);
        for (URI redirectLocation : redirectLocations) {
            redirects.add(redirectLocation.toString());
        }
        return redirects;
    } finally {
        if (response != null) {
            IOUtils.closeWhileHandlingException(response);
        }
    }
}
Also used : Header(org.apache.http.Header) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) URI(java.net.URI)

Example 27 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project spring-security-oauth by spring-projects.

the class ServerRunning method createRestTemplate.

public RestOperations createRestTemplate() {
    RestTemplate client = new RestTemplate();
    client.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {

        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            HttpClientContext context = HttpClientContext.create();
            Builder builder = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setAuthenticationEnabled(false).setRedirectsEnabled(false);
            context.setRequestConfig(builder.build());
            return context;
        }
    });
    client.setErrorHandler(new DefaultResponseErrorHandler() {

        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            return false;
        }
    });
    return client;
}
Also used : DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) Builder(org.apache.http.client.config.RequestConfig.Builder) RestTemplate(org.springframework.web.client.RestTemplate) HttpContext(org.apache.http.protocol.HttpContext) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) IOException(java.io.IOException) URI(java.net.URI) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) HttpMethod(org.springframework.http.HttpMethod)

Example 28 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project wildfly by wildfly.

the class Utils method makeCallWithBasicAuthn.

/**
     * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
     * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new
     * request is created with the provided credentials (basic authentication).
     *
     * @param url URL to which the request should be made
     * @param user Username (may be null)
     * @param pass Password (may be null)
     * @param expectedStatusCode expected status code returned from the requested server
     * @return HTTP response body
     * @throws IOException
     * @throws URISyntaxException
     */
public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode) throws IOException, URISyntaxException {
    LOGGER.trace("Requesting URL " + url);
    try (final CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        final HttpGet httpGet = new HttpGet(url.toURI());
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        }
        HttpEntity entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);
        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);
        HttpClientContext hc = new HttpClientContext();
        hc.setCredentialsProvider(new BasicCredentialsProvider());
        hc.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials);
        //enable auth
        response = httpClient.execute(httpGet, hc);
        statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) AuthScope(org.apache.http.auth.AuthScope) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 29 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project wildfly by wildfly.

the class JAASIdentityCachingTestCase method test.

/**
     * Test how many times is called login() method of {@link CustomLoginModule} and if the response from HelloBean is the
     * expected one.
     *
     * @param webAppURL
     * @throws Exception
     */
@Test
public void test(@ArquillianResource URL webAppURL) throws Exception {
    final URI greetingUri = new URI(webAppURL.toExternalForm() + HelloEJBCallServlet.SERVLET_PATH.substring(1) + "?" + HelloEJBCallServlet.PARAM_JNDI_NAME + "=" + URLEncoder.encode("java:app/" + JAR_BASE_NAME + "/" + HelloBean.class.getSimpleName(), "UTF-8"));
    final URI counterUri = new URI(webAppURL.toExternalForm() + LMCounterServlet.SERVLET_PATH.substring(1));
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", CustomLoginModule.PASSWORD);
    credentialsProvider.setCredentials(new AuthScope(greetingUri.getHost(), greetingUri.getPort()), credentials);
    try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final HttpGet getCounter = new HttpGet(counterUri);
        final HttpGet getGreeting = new HttpGet(greetingUri);
        HttpResponse response = httpClient.execute(getGreeting);
        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());
        //check if LoginModule #login() counter is initialized correctly
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        response = httpClient.execute(getCounter, context);
        assertEquals("0", EntityUtils.toString(response.getEntity()));
        //make 2 calls to the servlet
        response = httpClient.execute(getGreeting, context);
        assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));
        response = httpClient.execute(getGreeting, context);
        assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));
        //There should be only one call to login() method
        response = httpClient.execute(getCounter, context);
        assertEquals("1", EntityUtils.toString(response.getEntity()));
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) AuthScope(org.apache.http.auth.AuthScope) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) URI(java.net.URI) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Test(org.junit.Test)

Example 30 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project wildfly by wildfly.

the class CookieUnitTestCase method testCookieRetrievedCorrectly.

@Test
public void testCookieRetrievedCorrectly() throws Exception {
    log.trace("testCookieRetrievedCorrectly()");
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpClientContext context = HttpClientContext.create();
        HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieServlet"), context);
        // assert that we are able to hit servlet successfully
        int postStatusCode = response.getStatusLine().getStatusCode();
        Header[] postErrorHeaders = response.getHeaders("X-Exception");
        assertTrue("Wrong response code: " + postStatusCode, postStatusCode == HttpURLConnection.HTTP_OK);
        assertTrue("X-Exception(" + Arrays.toString(postErrorHeaders) + ") is null", postErrorHeaders.length == 0);
        List<Cookie> cookies = context.getCookieStore().getCookies();
        assertTrue("Sever did not set expired cookie on client", checkNoExpiredCookie(cookies));
        for (Cookie cookie : cookies) {
            log.trace("Cookie : " + cookie);
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            if (cookieName.equals("simpleCookie")) {
                assertTrue("cookie value should be jboss", cookieValue.equals("jboss"));
                assertEquals("cookie path", "/jbosstest-cookie", cookie.getPath());
                assertEquals("cookie persistence", false, cookie.isPersistent());
            } else if (cookieName.equals("withSpace")) {
                assertEquals("should be no quote in cookie with space", cookieValue.indexOf("\""), -1);
            } else if (cookieName.equals("comment")) {
                log.trace("comment in cookie: " + cookie.getComment());
                // RFC2109:Note that there is no Comment attribute in the Cookie request header
                // corresponding to the one in the Set-Cookie response header. The user
                // agent does not return the comment information to the origin server.
                assertTrue(cookie.getComment() == null);
            } else if (cookieName.equals("withComma")) {
                assertTrue("should contain a comma", cookieValue.indexOf(",") != -1);
            } else if (cookieName.equals("expireIn10Sec")) {
                Date now = new Date();
                log.trace("will sleep for 5 seconds to see if cookie expires");
                assertTrue("cookies should not be expired by now", !cookie.isExpired(new Date(now.getTime() + fiveSeconds)));
                log.trace("will sleep for 5 more secs and it should expire");
                assertTrue("cookies should be expired by now", cookie.isExpired(new Date(now.getTime() + 2 * fiveSeconds)));
            }
        }
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Header(org.apache.http.Header) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Date(java.util.Date) Test(org.junit.Test)

Aggregations

HttpClientContext (org.apache.http.client.protocol.HttpClientContext)44 IOException (java.io.IOException)18 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)17 HttpHost (org.apache.http.HttpHost)16 AuthScope (org.apache.http.auth.AuthScope)15 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)15 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 CredentialsProvider (org.apache.http.client.CredentialsProvider)12 BasicScheme (org.apache.http.impl.auth.BasicScheme)11 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)11 AuthCache (org.apache.http.client.AuthCache)10 HttpGet (org.apache.http.client.methods.HttpGet)10 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)10 HttpResponse (org.apache.http.HttpResponse)9 Header (org.apache.http.Header)8 URI (java.net.URI)6 HttpEntity (org.apache.http.HttpEntity)6 HttpContext (org.apache.http.protocol.HttpContext)5 SocketTimeoutException (java.net.SocketTimeoutException)4 HttpRequest (org.apache.http.HttpRequest)4