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.concurrent.Future;
32  
33  import org.apache.http.Consts;
34  import org.apache.http.HttpAsyncTestBase;
35  import org.apache.http.HttpEntity;
36  import org.apache.http.HttpException;
37  import org.apache.http.HttpHost;
38  import org.apache.http.HttpRequest;
39  import org.apache.http.HttpRequestInterceptor;
40  import org.apache.http.HttpResponse;
41  import org.apache.http.HttpResponseInterceptor;
42  import org.apache.http.HttpStatus;
43  import org.apache.http.auth.AUTH;
44  import org.apache.http.auth.AuthScope;
45  import org.apache.http.auth.Credentials;
46  import org.apache.http.auth.UsernamePasswordCredentials;
47  import org.apache.http.client.CredentialsProvider;
48  import org.apache.http.client.methods.HttpGet;
49  import org.apache.http.config.ConnectionConfig;
50  import org.apache.http.entity.StringEntity;
51  import org.apache.http.impl.DefaultConnectionReuseStrategy;
52  import org.apache.http.impl.DefaultHttpResponseFactory;
53  import org.apache.http.impl.nio.DefaultNHttpServerConnection;
54  import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory;
55  import org.apache.http.impl.nio.client.HttpAsyncClients;
56  import org.apache.http.localserver.RequestBasicAuth;
57  import org.apache.http.nio.NHttpConnectionFactory;
58  import org.apache.http.nio.protocol.BasicAsyncRequestHandler;
59  import org.apache.http.nio.protocol.HttpAsyncExpectationVerifier;
60  import org.apache.http.nio.protocol.HttpAsyncRequestHandlerMapper;
61  import org.apache.http.nio.protocol.HttpAsyncService;
62  import org.apache.http.nio.protocol.UriHttpAsyncRequestHandlerMapper;
63  import org.apache.http.nio.reactor.IOReactorStatus;
64  import org.apache.http.nio.reactor.ListenerEndpoint;
65  import org.apache.http.protocol.HttpContext;
66  import org.apache.http.protocol.HttpRequestHandler;
67  import org.apache.http.protocol.ImmutableHttpProcessor;
68  import org.apache.http.protocol.ResponseConnControl;
69  import org.apache.http.protocol.ResponseContent;
70  import org.apache.http.protocol.ResponseDate;
71  import org.apache.http.protocol.ResponseServer;
72  import org.apache.http.util.EntityUtils;
73  import org.junit.After;
74  import org.junit.Assert;
75  import org.junit.Before;
76  import org.junit.Test;
77  
78  public class TestClientAuthenticationFallBack extends HttpAsyncTestBase {
79  
80      @Before
81      public void setUp() throws Exception {
82          initServer();
83          initConnectionManager();
84      }
85  
86      @After
87      public void tearDown() throws Exception {
88          shutDownClient();
89          shutDownServer();
90      }
91  
92      @Override
93      public void initServer() throws Exception {
94          super.initServer();
95          this.serverHttpProc = new ImmutableHttpProcessor(
96                  new HttpRequestInterceptor[] {
97                          new RequestBasicAuth()
98                  },
99                  new HttpResponseInterceptor[] {
100                         new ResponseDate(),
101                         new ResponseServer(),
102                         new ResponseContent(),
103                         new ResponseConnControl(),
104                         new ResponseBasicUnauthorized()
105                 }
106         );
107     }
108 
109     @Override
110     protected NHttpConnectionFactory<DefaultNHttpServerConnection> createServerConnectionFactory(
111             final ConnectionConfig config) throws Exception {
112         return new DefaultNHttpServerConnectionFactory(config);
113     }
114 
115     @Override
116     protected String getSchemeName() {
117         return "http";
118     }
119 
120     private HttpHost start(
121             final HttpAsyncRequestHandlerMapper requestHandlerResolver,
122             final HttpAsyncExpectationVerifier expectationVerifier) throws Exception {
123         final HttpAsyncService serviceHandler = new HttpAsyncService(
124                 this.serverHttpProc,
125                 DefaultConnectionReuseStrategy.INSTANCE,
126                 DefaultHttpResponseFactory.INSTANCE,
127                 requestHandlerResolver,
128                 expectationVerifier);
129         this.server.start(serviceHandler);
130         this.httpclient.start();
131 
132         final ListenerEndpoint endpoint = this.server.getListenerEndpoint();
133         endpoint.waitFor();
134 
135         Assert.assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
136         final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
137         return new HttpHost("localhost", address.getPort(), getSchemeName());
138     }
139 
140     public class ResponseBasicUnauthorized implements HttpResponseInterceptor {
141 
142         public void process(
143                 final HttpResponse response,
144                 final HttpContext context) throws HttpException, IOException {
145             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
146                 response.addHeader(AUTH.WWW_AUTH, "Digest realm=\"test realm\" invalid");
147                 response.addHeader(AUTH.WWW_AUTH, "Basic realm=\"test realm\"");
148             }
149         }
150 
151     }
152 
153     static class AuthHandler implements HttpRequestHandler {
154 
155         public void handle(
156                 final HttpRequest request,
157                 final HttpResponse response,
158                 final HttpContext context) throws HttpException, IOException {
159             final String creds = (String) context.getAttribute("creds");
160             if (creds == null || !creds.equals("test:test")) {
161                 response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
162             } else {
163                 response.setStatusCode(HttpStatus.SC_OK);
164                 final StringEntity entity = new StringEntity("success", Consts.ASCII);
165                 response.setEntity(entity);
166             }
167         }
168 
169     }
170 
171     static class TestCredentialsProvider implements CredentialsProvider {
172 
173         private final Credentials creds;
174         private AuthScope authscope;
175 
176         TestCredentialsProvider(final Credentials creds) {
177             super();
178             this.creds = creds;
179         }
180 
181         public void clear() {
182         }
183 
184         public Credentials getCredentials(final AuthScope authscope) {
185             this.authscope = authscope;
186             return this.creds;
187         }
188 
189         public void setCredentials(final AuthScope authscope, final Credentials credentials) {
190         }
191 
192         public AuthScope getAuthScope() {
193             return this.authscope;
194         }
195 
196     }
197 
198     @Test
199     public void testBasicAuthenticationSuccess() throws Exception {
200         final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper();
201         registry.register("*", new BasicAsyncRequestHandler(new AuthHandler()));
202 
203         final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
204                 new UsernamePasswordCredentials("test", "test"));
205 
206         this.httpclient = HttpAsyncClients.custom()
207             .setConnectionManager(this.connMgr)
208             .setDefaultCredentialsProvider(credsProvider)
209             .build();
210 
211         final HttpHost target = start(registry, null);
212 
213         final HttpGet httpget = new HttpGet("/");
214 
215         final Future<HttpResponse> future = this.httpclient.execute(target, httpget, null);
216         final HttpResponse response = future.get();
217         Assert.assertNotNull(response);
218         final HttpEntity entity = response.getEntity();
219         Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
220         Assert.assertNotNull(entity);
221         EntityUtils.consume(entity);
222         final AuthScope authscope = credsProvider.getAuthScope();
223         Assert.assertNotNull(authscope);
224         Assert.assertEquals("test realm", authscope.getRealm());
225     }
226 
227 }