View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.testing.async;
28  
29  import java.util.Arrays;
30  import java.util.Collection;
31  import java.util.concurrent.Future;
32  
33  import org.apache.hc.client5.http.AuthenticationStrategy;
34  import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
35  import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
36  import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
37  import org.apache.hc.client5.http.auth.AuthSchemeFactory;
38  import org.apache.hc.client5.http.auth.AuthScope;
39  import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
40  import org.apache.hc.client5.http.config.RequestConfig;
41  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
42  import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder;
43  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
44  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
45  import org.apache.hc.client5.http.protocol.HttpClientContext;
46  import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
47  import org.apache.hc.client5.testing.BasicTestAuthenticator;
48  import org.apache.hc.client5.testing.SSLTestContexts;
49  import org.apache.hc.core5.function.Decorator;
50  import org.apache.hc.core5.function.Supplier;
51  import org.apache.hc.core5.http.HeaderElements;
52  import org.apache.hc.core5.http.HttpHeaders;
53  import org.apache.hc.core5.http.HttpHost;
54  import org.apache.hc.core5.http.HttpResponse;
55  import org.apache.hc.core5.http.HttpStatus;
56  import org.apache.hc.core5.http.HttpVersion;
57  import org.apache.hc.core5.http.URIScheme;
58  import org.apache.hc.core5.http.config.Http1Config;
59  import org.apache.hc.core5.http.config.Lookup;
60  import org.apache.hc.core5.http.impl.HttpProcessors;
61  import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
62  import org.junit.Assert;
63  import org.junit.Rule;
64  import org.junit.Test;
65  import org.junit.rules.ExternalResource;
66  import org.junit.runner.RunWith;
67  import org.junit.runners.Parameterized;
68  
69  @RunWith(Parameterized.class)
70  public class TestHttp1ClientAuthentication extends AbstractHttpAsyncClientAuthentication<CloseableHttpAsyncClient> {
71  
72      @Parameterized.Parameters(name = "HTTP/1.1 {0}")
73      public static Collection<Object[]> protocols() {
74          return Arrays.asList(new Object[][]{
75                  {URIScheme.HTTP},
76                  {URIScheme.HTTPS},
77          });
78      }
79  
80      protected HttpAsyncClientBuilder clientBuilder;
81      protected PoolingAsyncClientConnectionManager connManager;
82  
83      @Rule
84      public ExternalResource connManagerResource = new ExternalResource() {
85  
86          @Override
87          protected void before() throws Throwable {
88              connManager = PoolingAsyncClientConnectionManagerBuilder.create()
89                      .setTlsStrategy(new DefaultClientTlsStrategy(SSLTestContexts.createClientSSLContext()))
90                      .build();
91          }
92  
93          @Override
94          protected void after() {
95              if (connManager != null) {
96                  connManager.close();
97                  connManager = null;
98              }
99          }
100 
101     };
102 
103     @Rule
104     public ExternalResource clientBuilderResource = new ExternalResource() {
105 
106         @Override
107         protected void before() throws Throwable {
108             clientBuilder = HttpAsyncClientBuilder.create()
109                     .setDefaultRequestConfig(RequestConfig.custom()
110                             .setConnectionRequestTimeout(TIMEOUT)
111                             .setConnectTimeout(TIMEOUT)
112                             .build())
113                     .setConnectionManager(connManager);
114         }
115 
116     };
117 
118     public TestHttp1ClientAuthentication(final URIScheme scheme) {
119         super(scheme, HttpVersion.HTTP_1_1);
120     }
121 
122     @Override
123     void setDefaultAuthSchemeRegistry(final Lookup<AuthSchemeFactory> authSchemeRegistry) {
124         clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
125     }
126 
127     @Override
128     void setTargetAuthenticationStrategy(final AuthenticationStrategy targetAuthStrategy) {
129         clientBuilder.setTargetAuthenticationStrategy(targetAuthStrategy);
130     }
131 
132     @Override
133     protected CloseableHttpAsyncClient createClient() throws Exception {
134         return clientBuilder.build();
135     }
136 
137     @Test
138     public void testBasicAuthenticationSuccessNonPersistentConnection() throws Exception {
139         server.register("*", new Supplier<AsyncServerExchangeHandler>() {
140 
141             @Override
142             public AsyncServerExchangeHandler get() {
143                 return new AsyncEchoHandler();
144             }
145 
146         });
147         final HttpHost target = start(
148                 HttpProcessors.server(),
149                 new Decorator<AsyncServerExchangeHandler>() {
150 
151                     @Override
152                     public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
153                         return new AuthenticatingAsyncDecorator(exchangeHandler, new BasicTestAuthenticator("test:test", "test realm")) {
154 
155                             @Override
156                             protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
157                                 unauthorized.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
158                             }
159                         };
160                     }
161 
162                 },
163                 Http1Config.DEFAULT);
164 
165         final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
166                 new UsernamePasswordCredentials("test", "test".toCharArray()));
167         final HttpClientContext context = HttpClientContext.create();
168         context.setCredentialsProvider(credsProvider);
169 
170         final SimpleHttpRequest request = SimpleRequestBuilder.get()
171                 .setHttpHost(target)
172                 .setPath("/")
173                 .build();
174         final Future<SimpleHttpResponse> future = httpclient.execute(request, context, null);
175         final HttpResponse response = future.get();
176 
177         Assert.assertNotNull(response);
178         Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
179         final AuthScope authscope = credsProvider.getAuthScope();
180         Assert.assertNotNull(authscope);
181         Assert.assertEquals("test realm", authscope.getRealm());
182     }
183 
184 }