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.impl.client.integration;
28  
29  import java.io.IOException;
30  import java.util.Arrays;
31  import java.util.concurrent.atomic.AtomicLong;
32  
33  import org.apache.http.Consts;
34  import org.apache.http.HttpEntity;
35  import org.apache.http.HttpException;
36  import org.apache.http.HttpHost;
37  import org.apache.http.HttpRequest;
38  import org.apache.http.HttpResponse;
39  import org.apache.http.HttpResponseInterceptor;
40  import org.apache.http.HttpStatus;
41  import org.apache.http.auth.AUTH;
42  import org.apache.http.auth.AuthScheme;
43  import org.apache.http.auth.AuthSchemeProvider;
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.config.RequestConfig;
49  import org.apache.http.client.methods.HttpGet;
50  import org.apache.http.client.protocol.HttpClientContext;
51  import org.apache.http.config.Registry;
52  import org.apache.http.config.RegistryBuilder;
53  import org.apache.http.entity.StringEntity;
54  import org.apache.http.impl.auth.BasicScheme;
55  import org.apache.http.impl.auth.BasicSchemeFactory;
56  import org.apache.http.impl.client.TargetAuthenticationStrategy;
57  import org.apache.http.localserver.LocalServerTestBase;
58  import org.apache.http.localserver.RequestBasicAuth;
59  import org.apache.http.protocol.HttpContext;
60  import org.apache.http.protocol.HttpProcessor;
61  import org.apache.http.protocol.HttpProcessorBuilder;
62  import org.apache.http.protocol.HttpRequestHandler;
63  import org.apache.http.protocol.ResponseConnControl;
64  import org.apache.http.protocol.ResponseContent;
65  import org.apache.http.protocol.ResponseDate;
66  import org.apache.http.protocol.ResponseServer;
67  import org.apache.http.util.EntityUtils;
68  import org.junit.Assert;
69  import org.junit.Before;
70  import org.junit.Test;
71  
72  public class TestClientReauthentication extends LocalServerTestBase {
73  
74      public class ResponseBasicUnauthorized implements HttpResponseInterceptor {
75  
76          @Override
77          public void process(
78                  final HttpResponse response,
79                  final HttpContext context) throws HttpException, IOException {
80              if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
81                  response.addHeader(AUTH.WWW_AUTH, "MyBasic realm=\"test realm\"");
82              }
83          }
84  
85      }
86  
87      @Before @Override
88      public void setUp() throws Exception {
89          super.setUp();
90          final HttpProcessor httpproc = HttpProcessorBuilder.create()
91              .add(new ResponseDate())
92              .add(new ResponseServer(LocalServerTestBase.ORIGIN))
93              .add(new ResponseContent())
94              .add(new ResponseConnControl())
95              .add(new RequestBasicAuth())
96              .add(new ResponseBasicUnauthorized()).build();
97          this.serverBootstrap.setHttpProcessor(httpproc);
98      }
99  
100     static class AuthHandler implements HttpRequestHandler {
101 
102         private final AtomicLong count = new AtomicLong(0);
103 
104         @Override
105         public void handle(
106                 final HttpRequest request,
107                 final HttpResponse response,
108                 final HttpContext context) throws HttpException, IOException {
109             final String creds = (String) context.getAttribute("creds");
110             if (creds == null || !creds.equals("test:test")) {
111                 response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
112             } else {
113                 // Make client re-authenticate on each fourth request
114                 if (this.count.incrementAndGet() % 4 == 0) {
115                     response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
116                 } else {
117                     response.setStatusCode(HttpStatus.SC_OK);
118                     final StringEntity entity = new StringEntity("success", Consts.ASCII);
119                     response.setEntity(entity);
120                 }
121             }
122         }
123 
124     }
125 
126     static class TestCredentialsProvider implements CredentialsProvider {
127 
128         private final Credentials creds;
129         private AuthScope authscope;
130 
131         TestCredentialsProvider(final Credentials creds) {
132             super();
133             this.creds = creds;
134         }
135 
136         @Override
137         public void clear() {
138         }
139 
140         @Override
141         public Credentials getCredentials(final AuthScope authscope) {
142             this.authscope = authscope;
143             return this.creds;
144         }
145 
146         @Override
147         public void setCredentials(final AuthScope authscope, final Credentials credentials) {
148         }
149 
150         public AuthScope getAuthScope() {
151             return this.authscope;
152         }
153 
154     }
155 
156     @Test
157     public void testBasicAuthenticationSuccess() throws Exception {
158         this.serverBootstrap.registerHandler("*", new AuthHandler());
159 
160         final BasicSchemeFactory myBasicAuthSchemeFactory = new BasicSchemeFactory() {
161 
162             @Override
163             public AuthScheme create(final HttpContext context) {
164                 return new BasicScheme() {
165                     private static final long serialVersionUID = 1L;
166 
167                     @Override
168                     public String getSchemeName() {
169                         return "MyBasic";
170                     }
171 
172                 };
173             }
174 
175         };
176 
177         final TargetAuthenticationStrategy myAuthStrategy = new TargetAuthenticationStrategy() {
178 
179             @Override
180             protected boolean isCachable(final AuthScheme authScheme) {
181                 return "MyBasic".equalsIgnoreCase(authScheme.getSchemeName());
182             }
183 
184         };
185 
186         final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
187                 new UsernamePasswordCredentials("test", "test"));
188 
189         final RequestConfig config = RequestConfig.custom()
190             .setTargetPreferredAuthSchemes(Arrays.asList("MyBasic"))
191             .build();
192         final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
193             .register("MyBasic", myBasicAuthSchemeFactory)
194             .build();
195         this.httpclient = this.clientBuilder
196             .setDefaultAuthSchemeRegistry(authSchemeRegistry)
197             .setTargetAuthenticationStrategy(myAuthStrategy)
198             .setDefaultCredentialsProvider(credsProvider)
199             .build();
200 
201         final HttpHost target = start();
202 
203         final HttpClientContext context = HttpClientContext.create();
204         for (int i = 0; i < 10; i++) {
205             final HttpGet httpget = new HttpGet("/");
206             httpget.setConfig(config);
207             final HttpResponse response = this.httpclient.execute(target, httpget, context);
208             final HttpEntity entity = response.getEntity();
209             Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
210             Assert.assertNotNull(entity);
211             EntityUtils.consume(entity);
212         }
213     }
214 
215 }