Search in sources :

Example 26 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class AbstractHttpAsyncClientAuthentication method testReauthentication.

@Test
public void testReauthentication() throws Exception {
    server.register("*", AsyncEchoHandler::new);
    final CredentialsProvider credsProvider = Mockito.mock(CredentialsProvider.class);
    Mockito.when(credsProvider.getCredentials(Mockito.any(), Mockito.any())).thenReturn(new UsernamePasswordCredentials("test", "test".toCharArray()));
    final Registry<AuthSchemeFactory> authSchemeRegistry = RegistryBuilder.<AuthSchemeFactory>create().register("MyBasic", context -> new BasicScheme() {

        private static final long serialVersionUID = 1L;

        @Override
        public String getName() {
            return "MyBasic";
        }
    }).build();
    setDefaultAuthSchemeRegistry(authSchemeRegistry);
    final Authenticator authenticator = new BasicTestAuthenticator("test:test", "test realm") {

        private final AtomicLong count = new AtomicLong(0);

        @Override
        public boolean authenticate(final URIAuthority authority, final String requestUri, final String credentials) {
            final boolean authenticated = super.authenticate(authority, requestUri, credentials);
            if (authenticated) {
                return this.count.incrementAndGet() % 4 != 0;
            }
            return false;
        }
    };
    final HttpHost target = start(exchangeHandler -> new AuthenticatingAsyncDecorator(exchangeHandler, authenticator) {

        @Override
        protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
            unauthorized.removeHeaders(HttpHeaders.WWW_AUTHENTICATE);
            unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\"");
        }
    });
    final RequestConfig config = RequestConfig.custom().setTargetPreferredAuthSchemes(Collections.singletonList("MyBasic")).build();
    final HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    for (int i = 0; i < 10; i++) {
        final SimpleHttpRequest request = SimpleRequestBuilder.get().setHttpHost(target).setPath("/").build();
        request.setConfig(config);
        final Future<SimpleHttpResponse> future = httpclient.execute(request, context, null);
        final SimpleHttpResponse response = future.get();
        Assertions.assertNotNull(response);
        Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
    }
}
Also used : CoreMatchers(org.hamcrest.CoreMatchers) Arrays(java.util.Arrays) AuthScope(org.apache.hc.client5.http.auth.AuthScope) H2Config(org.apache.hc.core5.http2.config.H2Config) Lookup(org.apache.hc.core5.http.config.Lookup) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) Future(java.util.concurrent.Future) URIAuthority(org.apache.hc.core5.net.URIAuthority) HttpProcessors(org.apache.hc.core5.http.impl.HttpProcessors) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) Http1Config(org.apache.hc.core5.http.config.Http1Config) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) AuthCache(org.apache.hc.client5.http.auth.AuthCache) AuthSchemeFactory(org.apache.hc.client5.http.auth.AuthSchemeFactory) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) Decorator(org.apache.hc.core5.function.Decorator) DefaultAuthenticationStrategy(org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy) Collectors(java.util.stream.Collectors) RegistryBuilder(org.apache.hc.core5.http.config.RegistryBuilder) H2Processors(org.apache.hc.core5.http2.impl.H2Processors) Queue(java.util.Queue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) CredentialsProvider(org.apache.hc.client5.http.auth.CredentialsProvider) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) AuthenticationStrategy(org.apache.hc.client5.http.AuthenticationStrategy) HttpResponseInterceptor(org.apache.hc.core5.http.HttpResponseInterceptor) Registry(org.apache.hc.core5.http.config.Registry) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) CredentialsProviderBuilder(org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder) HttpVersion(org.apache.hc.core5.http.HttpVersion) HttpResponse(org.apache.hc.core5.http.HttpResponse) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) Authenticator(org.apache.hc.client5.testing.auth.Authenticator) StandardAuthScheme(org.apache.hc.client5.http.auth.StandardAuthScheme) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) BasicTestAuthenticator(org.apache.hc.client5.testing.BasicTestAuthenticator) ProtocolException(org.apache.hc.core5.http.ProtocolException) Test(org.junit.Test) URIScheme(org.apache.hc.core5.http.URIScheme) SimpleRequestBuilder(org.apache.hc.client5.http.async.methods.SimpleRequestBuilder) BasicResponseBuilder(org.apache.hc.core5.http.support.BasicResponseBuilder) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) HttpHeaders(org.apache.hc.core5.http.HttpHeaders) Mockito(org.mockito.Mockito) HttpHost(org.apache.hc.core5.http.HttpHost) ContentType(org.apache.hc.core5.http.ContentType) Assertions(org.junit.jupiter.api.Assertions) HttpRequestInterceptor(org.apache.hc.core5.http.HttpRequestInterceptor) HttpStatus(org.apache.hc.core5.http.HttpStatus) Collections(java.util.Collections) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) AuthSchemeFactory(org.apache.hc.client5.http.auth.AuthSchemeFactory) URIAuthority(org.apache.hc.core5.net.URIAuthority) BasicTestAuthenticator(org.apache.hc.client5.testing.BasicTestAuthenticator) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) CredentialsProvider(org.apache.hc.client5.http.auth.CredentialsProvider) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) AtomicLong(java.util.concurrent.atomic.AtomicLong) HttpHost(org.apache.hc.core5.http.HttpHost) Authenticator(org.apache.hc.client5.testing.auth.Authenticator) BasicTestAuthenticator(org.apache.hc.client5.testing.BasicTestAuthenticator) Test(org.junit.Test)

Example 27 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class AbstractHttpAsyncClientAuthentication method testAuthenticationUserinfoInRequestFailure.

@Test
public void testAuthenticationUserinfoInRequestFailure() throws Exception {
    server.register("*", AsyncEchoHandler::new);
    final HttpHost target = start();
    final HttpClientContext context = HttpClientContext.create();
    final Future<SimpleHttpResponse> future = httpclient.execute(SimpleRequestBuilder.get().setScheme(target.getSchemeName()).setAuthority(new URIAuthority("test:test", target.getHostName(), target.getPort())).setPath("/").build(), context, null);
    final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future.get());
    assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) URIAuthority(org.apache.hc.core5.net.URIAuthority) HttpHost(org.apache.hc.core5.http.HttpHost) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) ExecutionException(java.util.concurrent.ExecutionException) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) Test(org.junit.Test)

Example 28 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class TestHttp1AsyncStatefulConnManagement method testRouteSpecificPoolRecylcing.

@Test
public void testRouteSpecificPoolRecylcing() throws Exception {
    server.register("*", () -> new AbstractSimpleServerExchangeHandler() {

        @Override
        protected SimpleHttpResponse handle(final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
            final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
            response.setBody("Whatever", ContentType.TEXT_PLAIN);
            return response;
        }
    });
    // This tests what happens when a maxed connection pool needs
    // to kill the last idle connection to a route to build a new
    // one to the same route.
    final UserTokenHandler userTokenHandler = (route, context) -> context.getAttribute("user");
    clientBuilder.setUserTokenHandler(userTokenHandler);
    final HttpHost target = start();
    final int maxConn = 2;
    // We build a client with 2 max active // connections, and 2 max per route.
    connManager.setMaxTotal(maxConn);
    connManager.setDefaultMaxPerRoute(maxConn);
    // Bottom of the pool : a *keep alive* connection to Route 1.
    final HttpContext context1 = new BasicHttpContext();
    context1.setAttribute("user", "stuff");
    final SimpleHttpRequest request1 = SimpleRequestBuilder.get().setHttpHost(target).setPath("/").build();
    final Future<SimpleHttpResponse> future1 = httpclient.execute(request1, context1, null);
    final HttpResponse response1 = future1.get();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    // The ConnPoolByRoute now has 1 free connection, out of 2 max
    // The ConnPoolByRoute has one RouteSpcfcPool, that has one free connection
    // for [localhost][stuff]
    Thread.sleep(100);
    // Send a very simple HTTP get (it MUST be simple, no auth, no proxy, no 302, no 401, ...)
    // Send it to another route. Must be a keepalive.
    final HttpContext context2 = new BasicHttpContext();
    final SimpleHttpRequest request2 = SimpleRequestBuilder.get().setScheme(target.getSchemeName()).setAuthority(new URIAuthority("127.0.0.1", target.getPort())).setPath("/").build();
    final Future<SimpleHttpResponse> future2 = httpclient.execute(request2, context2, null);
    final HttpResponse response2 = future2.get();
    Assertions.assertNotNull(response2);
    Assertions.assertEquals(200, response2.getCode());
    // ConnPoolByRoute now has 2 free connexions, out of its 2 max.
    // The [localhost][stuff] RouteSpcfcPool is the same as earlier
    // And there is a [127.0.0.1][null] pool with 1 free connection
    Thread.sleep(100);
    // This will put the ConnPoolByRoute to the targeted state :
    // [localhost][stuff] will not get reused because this call is [localhost][null]
    // So the ConnPoolByRoute will need to kill one connection (it is maxed out globally).
    // The killed conn is the oldest, which means the first HTTPGet ([localhost][stuff]).
    // When this happens, the RouteSpecificPool becomes empty.
    final HttpContext context3 = new BasicHttpContext();
    final SimpleHttpRequest request3 = SimpleRequestBuilder.get().setHttpHost(target).setPath("/").build();
    final Future<SimpleHttpResponse> future3 = httpclient.execute(request3, context3, null);
    final HttpResponse response3 = future3.get();
    Assertions.assertNotNull(response3);
    Assertions.assertEquals(200, response3.getCode());
}
Also used : SSLTestContexts(org.apache.hc.client5.testing.SSLTestContexts) BasicHttpContext(org.apache.hc.core5.http.protocol.BasicHttpContext) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) Future(java.util.concurrent.Future) URIAuthority(org.apache.hc.core5.net.URIAuthority) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) HttpResponse(org.apache.hc.core5.http.HttpResponse) Http1Config(org.apache.hc.core5.http.config.Http1Config) ConnectionConfig(org.apache.hc.client5.http.config.ConnectionConfig) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) PoolingAsyncClientConnectionManager(org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager) PoolingAsyncClientConnectionManagerBuilder(org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder) EndpointDetails(org.apache.hc.core5.http.EndpointDetails) HttpException(org.apache.hc.core5.http.HttpException) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) HttpAsyncClientBuilder(org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder) Test(org.junit.Test) UserTokenHandler(org.apache.hc.client5.http.UserTokenHandler) SimpleRequestBuilder(org.apache.hc.client5.http.async.methods.SimpleRequestBuilder) HttpHost(org.apache.hc.core5.http.HttpHost) Rule(org.junit.Rule) ExternalResource(org.junit.rules.ExternalResource) ContentType(org.apache.hc.core5.http.ContentType) Assertions(org.junit.jupiter.api.Assertions) HttpStatus(org.apache.hc.core5.http.HttpStatus) DefaultClientTlsStrategy(org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy) URIAuthority(org.apache.hc.core5.net.URIAuthority) BasicHttpContext(org.apache.hc.core5.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.hc.core5.http.protocol.BasicHttpContext) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpException(org.apache.hc.core5.http.HttpException) UserTokenHandler(org.apache.hc.client5.http.UserTokenHandler) Test(org.junit.Test)

Example 29 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class AuthenticatingAsyncDecorator method handleRequest.

@Override
public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
    final Header h = request.getFirstHeader(HttpHeaders.AUTHORIZATION);
    final String challengeResponse = h != null ? authTokenExtractor.extract(h.getValue()) : null;
    final URIAuthority authority = request.getAuthority();
    final String requestUri = request.getRequestUri();
    final boolean authenticated = authenticator.authenticate(authority, requestUri, challengeResponse);
    final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
    final boolean expectContinue = expect != null && "100-continue".equalsIgnoreCase(expect.getValue());
    if (authenticated) {
        if (expectContinue) {
            responseChannel.sendInformation(new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE), context);
        }
        exchangeHandler.handleRequest(request, entityDetails, responseChannel, context);
    } else {
        final HttpResponse unauthorized = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
        final String realm = authenticator.getRealm(authority, requestUri);
        unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.BASIC + " realm=\"" + realm + "\"");
        customizeUnauthorizedResponse(unauthorized);
        final AsyncResponseProducer responseProducer = new BasicResponseProducer(unauthorized, new BasicAsyncEntityProducer("Unauthorized", ContentType.TEXT_PLAIN));
        responseProducerRef.set(responseProducer);
        responseProducer.sendResponse(responseChannel, context);
    }
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) URIAuthority(org.apache.hc.core5.net.URIAuthority) Header(org.apache.hc.core5.http.Header) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) BasicAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 30 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class TestCachingExecChain method testUsesVirtualHostForCacheKey.

@Test
public void testUsesVirtualHostForCacheKey() throws Exception {
    final ClassicHttpResponse response = HttpTestUtils.make200Response();
    response.setHeader("Cache-Control", "max-age=3600");
    Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(response);
    impl.execute(request, new ExecChain.Scope("test", route, request, mockExecRuntime, context), mockExecChain);
    Mockito.verify(mockExecChain, Mockito.times(1)).proceed(Mockito.any(), Mockito.any());
    request.setAuthority(new URIAuthority("bar.example.com"));
    impl.execute(request, new ExecChain.Scope("test", route, request, mockExecRuntime, context), mockExecChain);
    Mockito.verify(mockExecChain, Mockito.times(2)).proceed(Mockito.any(), Mockito.any());
    impl.execute(request, new ExecChain.Scope("test", route, request, mockExecRuntime, context), mockExecChain);
    Mockito.verify(mockExecChain, Mockito.times(2)).proceed(Mockito.any(), Mockito.any());
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) URIAuthority(org.apache.hc.core5.net.URIAuthority) ExecChain(org.apache.hc.client5.http.classic.ExecChain) Test(org.junit.jupiter.api.Test)

Aggregations

URIAuthority (org.apache.hc.core5.net.URIAuthority)63 Test (org.junit.jupiter.api.Test)32 HttpRequest (org.apache.hc.core5.http.HttpRequest)21 HttpHost (org.apache.hc.core5.http.HttpHost)17 Header (org.apache.hc.core5.http.Header)15 URI (java.net.URI)14 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)11 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)10 HttpException (org.apache.hc.core5.http.HttpException)9 IOException (java.io.IOException)8 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)8 ProtocolException (org.apache.hc.core5.http.ProtocolException)8 HttpResponse (org.apache.hc.core5.http.HttpResponse)7 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)7 HttpEntity (org.apache.hc.core5.http.HttpEntity)6 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 HttpRoute (org.apache.hc.client5.http.HttpRoute)5 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)5 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)5