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.http.nio.client.integration;
28  
29  import java.io.IOException;
30  import java.net.InetSocketAddress;
31  import java.util.Arrays;
32  import java.util.concurrent.Future;
33  import java.util.concurrent.atomic.AtomicLong;
34  
35  import org.apache.http.Consts;
36  import org.apache.http.HttpAsyncTestBase;
37  import org.apache.http.HttpEntity;
38  import org.apache.http.HttpException;
39  import org.apache.http.HttpHost;
40  import org.apache.http.HttpRequest;
41  import org.apache.http.HttpRequestInterceptor;
42  import org.apache.http.HttpResponse;
43  import org.apache.http.HttpResponseInterceptor;
44  import org.apache.http.HttpStatus;
45  import org.apache.http.auth.AUTH;
46  import org.apache.http.auth.AuthScheme;
47  import org.apache.http.auth.AuthSchemeProvider;
48  import org.apache.http.auth.AuthScope;
49  import org.apache.http.auth.Credentials;
50  import org.apache.http.auth.UsernamePasswordCredentials;
51  import org.apache.http.client.CredentialsProvider;
52  import org.apache.http.client.config.RequestConfig;
53  import org.apache.http.client.methods.HttpGet;
54  import org.apache.http.config.ConnectionConfig;
55  import org.apache.http.config.Registry;
56  import org.apache.http.config.RegistryBuilder;
57  import org.apache.http.entity.StringEntity;
58  import org.apache.http.impl.DefaultConnectionReuseStrategy;
59  import org.apache.http.impl.DefaultHttpResponseFactory;
60  import org.apache.http.impl.auth.BasicScheme;
61  import org.apache.http.impl.auth.BasicSchemeFactory;
62  import org.apache.http.impl.client.TargetAuthenticationStrategy;
63  import org.apache.http.impl.nio.DefaultNHttpServerConnection;
64  import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory;
65  import org.apache.http.impl.nio.client.HttpAsyncClients;
66  import org.apache.http.localserver.RequestBasicAuth;
67  import org.apache.http.nio.NHttpConnectionFactory;
68  import org.apache.http.nio.protocol.BasicAsyncRequestHandler;
69  import org.apache.http.nio.protocol.HttpAsyncExpectationVerifier;
70  import org.apache.http.nio.protocol.HttpAsyncRequestHandlerMapper;
71  import org.apache.http.nio.protocol.HttpAsyncService;
72  import org.apache.http.nio.protocol.UriHttpAsyncRequestHandlerMapper;
73  import org.apache.http.nio.reactor.IOReactorStatus;
74  import org.apache.http.nio.reactor.ListenerEndpoint;
75  import org.apache.http.protocol.BasicHttpContext;
76  import org.apache.http.protocol.HttpContext;
77  import org.apache.http.protocol.HttpRequestHandler;
78  import org.apache.http.protocol.ImmutableHttpProcessor;
79  import org.apache.http.protocol.ResponseConnControl;
80  import org.apache.http.protocol.ResponseContent;
81  import org.apache.http.protocol.ResponseDate;
82  import org.apache.http.protocol.ResponseServer;
83  import org.apache.http.util.EntityUtils;
84  import org.junit.After;
85  import org.junit.Assert;
86  import org.junit.Before;
87  import org.junit.Test;
88  
89  public class TestClientReauthentication extends HttpAsyncTestBase {
90  
91      @Before
92      public void setUp() throws Exception {
93          initServer();
94          initConnectionManager();
95      }
96  
97      @After
98      public void tearDown() throws Exception {
99          shutDownClient();
100         shutDownServer();
101     }
102 
103     @Override
104     public void initServer() throws Exception {
105         super.initServer();
106         this.serverHttpProc = new ImmutableHttpProcessor(
107                 new HttpRequestInterceptor[] {
108                         new RequestBasicAuth()
109                 },
110                 new HttpResponseInterceptor[] {
111                         new ResponseDate(),
112                         new ResponseServer(),
113                         new ResponseContent(),
114                         new ResponseConnControl(),
115                         new ResponseBasicUnauthorized()
116                 }
117         );
118     }
119 
120     @Override
121     protected NHttpConnectionFactory<DefaultNHttpServerConnection> createServerConnectionFactory(
122             final ConnectionConfig config) throws Exception {
123         return new DefaultNHttpServerConnectionFactory(config);
124     }
125 
126     @Override
127     protected String getSchemeName() {
128         return "http";
129     }
130 
131     private HttpHost start(
132             final HttpAsyncRequestHandlerMapper requestHandlerResolver,
133             final HttpAsyncExpectationVerifier expectationVerifier) throws Exception {
134         final HttpAsyncService serviceHandler = new HttpAsyncService(
135                 this.serverHttpProc,
136                 DefaultConnectionReuseStrategy.INSTANCE,
137                 DefaultHttpResponseFactory.INSTANCE,
138                 requestHandlerResolver,
139                 expectationVerifier);
140         this.server.start(serviceHandler);
141         this.httpclient.start();
142 
143         final ListenerEndpoint endpoint = this.server.getListenerEndpoint();
144         endpoint.waitFor();
145 
146         Assert.assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
147         final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
148         return new HttpHost("localhost", address.getPort(), getSchemeName());
149     }
150 
151     public class ResponseBasicUnauthorized implements HttpResponseInterceptor {
152 
153         public void process(
154                 final HttpResponse response,
155                 final HttpContext context) throws HttpException, IOException {
156             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
157                 response.addHeader(AUTH.WWW_AUTH, "MyBasic realm=\"test realm\"");
158             }
159         }
160 
161     }
162 
163     static class AuthHandler implements HttpRequestHandler {
164 
165         private final AtomicLong count = new AtomicLong(0);
166 
167         public void handle(
168                 final HttpRequest request,
169                 final HttpResponse response,
170                 final HttpContext context) throws HttpException, IOException {
171             final String creds = (String) context.getAttribute("creds");
172             if (creds == null || !creds.equals("test:test")) {
173                 response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
174             } else {
175                 // Make client re-authenticate on each fourth request
176                 if (this.count.incrementAndGet() % 4 == 0) {
177                     response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
178                 } else {
179                     response.setStatusCode(HttpStatus.SC_OK);
180                     final StringEntity entity = new StringEntity("success", Consts.ASCII);
181                     response.setEntity(entity);
182                 }
183             }
184         }
185 
186     }
187 
188     static class TestCredentialsProvider implements CredentialsProvider {
189 
190         private final Credentials creds;
191         private AuthScope authscope;
192 
193         TestCredentialsProvider(final Credentials creds) {
194             super();
195             this.creds = creds;
196         }
197 
198         public void clear() {
199         }
200 
201         public Credentials getCredentials(final AuthScope authscope) {
202             this.authscope = authscope;
203             return this.creds;
204         }
205 
206         public void setCredentials(final AuthScope authscope, final Credentials credentials) {
207         }
208 
209         public AuthScope getAuthScope() {
210             return this.authscope;
211         }
212 
213     }
214 
215     @Test
216     public void testBasicAuthenticationSuccess() throws Exception {
217         final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper();
218         registry.register("*", new BasicAsyncRequestHandler(new AuthHandler()));
219 
220         final BasicSchemeFactory myBasicAuthSchemeFactory = new BasicSchemeFactory() {
221 
222             @Override
223             public AuthScheme create(final HttpContext context) {
224                 return new BasicScheme() {
225 
226                     @Override
227                     public String getSchemeName() {
228                         return "MyBasic";
229                     }
230 
231                 };
232             }
233 
234         };
235 
236         final TargetAuthenticationStrategy myAuthStrategy = new TargetAuthenticationStrategy() {
237 
238             @Override
239             protected boolean isCachable(final AuthScheme authScheme) {
240                 return "MyBasic".equalsIgnoreCase(authScheme.getSchemeName());
241             }
242 
243         };
244 
245         final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
246                 new UsernamePasswordCredentials("test", "test"));
247 
248         final RequestConfig config = RequestConfig.custom()
249             .setTargetPreferredAuthSchemes(Arrays.asList("MyBasic"))
250             .build();
251         final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
252             .register("MyBasic", myBasicAuthSchemeFactory)
253             .build();
254         this.httpclient = HttpAsyncClients.custom()
255             .setDefaultAuthSchemeRegistry(authSchemeRegistry)
256             .setTargetAuthenticationStrategy(myAuthStrategy)
257             .setDefaultCredentialsProvider(credsProvider)
258             .build();
259 
260         final HttpHost target = start(registry, null);
261 
262         final HttpContext context = new BasicHttpContext();
263         for (int i = 0; i < 10; i++) {
264             final HttpGet httpget = new HttpGet("/");
265             httpget.setConfig(config);
266             final Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
267             final HttpResponse response = future.get();
268             Assert.assertNotNull(response);
269             final HttpEntity entity = response.getEntity();
270             Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
271             Assert.assertNotNull(entity);
272             EntityUtils.consume(entity);
273         }
274     }
275 
276 }