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  
28  package org.apache.http.impl.client;
29  
30  import java.util.Arrays;
31  import java.util.Collection;
32  import java.util.Collections;
33  import java.util.HashMap;
34  import java.util.LinkedList;
35  import java.util.List;
36  import java.util.Locale;
37  import java.util.Map;
38  import java.util.Queue;
39  
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  import org.apache.http.FormattedHeader;
43  import org.apache.http.Header;
44  import org.apache.http.HttpHost;
45  import org.apache.http.HttpResponse;
46  import org.apache.http.annotation.Immutable;
47  import org.apache.http.auth.AuthOption;
48  import org.apache.http.auth.AuthScheme;
49  import org.apache.http.auth.AuthSchemeProvider;
50  import org.apache.http.auth.AuthScope;
51  import org.apache.http.auth.Credentials;
52  import org.apache.http.auth.MalformedChallengeException;
53  import org.apache.http.client.AuthCache;
54  import org.apache.http.client.AuthenticationStrategy;
55  import org.apache.http.client.CredentialsProvider;
56  import org.apache.http.client.config.AuthSchemes;
57  import org.apache.http.client.config.RequestConfig;
58  import org.apache.http.client.protocol.HttpClientContext;
59  import org.apache.http.config.Lookup;
60  import org.apache.http.protocol.HTTP;
61  import org.apache.http.protocol.HttpContext;
62  import org.apache.http.util.Args;
63  import org.apache.http.util.CharArrayBuffer;
64  
65  @Immutable
66  abstract class AuthenticationStrategyImpl implements AuthenticationStrategy {
67  
68      private final Log log = LogFactory.getLog(getClass());
69  
70      private static final List<String> DEFAULT_SCHEME_PRIORITY =
71          Collections.unmodifiableList(Arrays.asList(AuthSchemes.SPNEGO,
72                  AuthSchemes.KERBEROS,
73                  AuthSchemes.NTLM,
74                  AuthSchemes.DIGEST,
75                  AuthSchemes.BASIC));
76  
77      private final int challengeCode;
78      private final String headerName;
79  
80      AuthenticationStrategyImpl(final int challengeCode, final String headerName) {
81          super();
82          this.challengeCode = challengeCode;
83          this.headerName = headerName;
84      }
85  
86      public boolean isAuthenticationRequested(
87              final HttpHost authhost,
88              final HttpResponse response,
89              final HttpContext context) {
90          Args.notNull(response, "HTTP response");
91          final int status = response.getStatusLine().getStatusCode();
92          return status == this.challengeCode;
93      }
94  
95      public Map<String, Header> getChallenges(
96              final HttpHost authhost,
97              final HttpResponse response,
98              final HttpContext context) throws MalformedChallengeException {
99          Args.notNull(response, "HTTP response");
100         final Header[] headers = response.getHeaders(this.headerName);
101         final Map<String, Header> map = new HashMap<String, Header>(headers.length);
102         for (final Header header : headers) {
103             final CharArrayBuffer buffer;
104             int pos;
105             if (header instanceof FormattedHeader) {
106                 buffer = ((FormattedHeader) header).getBuffer();
107                 pos = ((FormattedHeader) header).getValuePos();
108             } else {
109                 final String s = header.getValue();
110                 if (s == null) {
111                     throw new MalformedChallengeException("Header value is null");
112                 }
113                 buffer = new CharArrayBuffer(s.length());
114                 buffer.append(s);
115                 pos = 0;
116             }
117             while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
118                 pos++;
119             }
120             final int beginIndex = pos;
121             while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
122                 pos++;
123             }
124             final int endIndex = pos;
125             final String s = buffer.substring(beginIndex, endIndex);
126             map.put(s.toLowerCase(Locale.US), header);
127         }
128         return map;
129     }
130 
131     abstract Collection<String> getPreferredAuthSchemes(RequestConfig config);
132 
133     public Queue<AuthOption> select(
134             final Map<String, Header> challenges,
135             final HttpHost authhost,
136             final HttpResponse response,
137             final HttpContext context) throws MalformedChallengeException {
138         Args.notNull(challenges, "Map of auth challenges");
139         Args.notNull(authhost, "Host");
140         Args.notNull(response, "HTTP response");
141         Args.notNull(context, "HTTP context");
142         final HttpClientContext clientContext = HttpClientContext.adapt(context);
143 
144         final Queue<AuthOption> options = new LinkedList<AuthOption>();
145         final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
146         if (registry == null) {
147             this.log.debug("Auth scheme registry not set in the context");
148             return options;
149         }
150         final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
151         if (credsProvider == null) {
152             this.log.debug("Credentials provider not set in the context");
153             return options;
154         }
155         final RequestConfig config = clientContext.getRequestConfig();
156         Collection<String> authPrefs = getPreferredAuthSchemes(config);
157         if (authPrefs == null) {
158             authPrefs = DEFAULT_SCHEME_PRIORITY;
159         }
160         if (this.log.isDebugEnabled()) {
161             this.log.debug("Authentication schemes in the order of preference: " + authPrefs);
162         }
163 
164         for (final String id: authPrefs) {
165             final Header challenge = challenges.get(id.toLowerCase(Locale.US));
166             if (challenge != null) {
167                 final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
168                 if (authSchemeProvider == null) {
169                     if (this.log.isWarnEnabled()) {
170                         this.log.warn("Authentication scheme " + id + " not supported");
171                         // Try again
172                     }
173                     continue;
174                 }
175                 final AuthScheme authScheme = authSchemeProvider.create(context);
176                 authScheme.processChallenge(challenge);
177 
178                 final AuthScope authScope = new AuthScope(
179                         authhost.getHostName(),
180                         authhost.getPort(),
181                         authScheme.getRealm(),
182                         authScheme.getSchemeName());
183 
184                 final Credentials credentials = credsProvider.getCredentials(authScope);
185                 if (credentials != null) {
186                     options.add(new AuthOption(authScheme, credentials));
187                 }
188             } else {
189                 if (this.log.isDebugEnabled()) {
190                     this.log.debug("Challenge for " + id + " authentication scheme not available");
191                     // Try again
192                 }
193             }
194         }
195         return options;
196     }
197 
198     public void authSucceeded(
199             final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
200         Args.notNull(authhost, "Host");
201         Args.notNull(authScheme, "Auth scheme");
202         Args.notNull(context, "HTTP context");
203 
204         final HttpClientContext clientContext = HttpClientContext.adapt(context);
205 
206         if (isCachable(authScheme)) {
207             AuthCache authCache = clientContext.getAuthCache();
208             if (authCache == null) {
209                 authCache = new BasicAuthCache();
210                 clientContext.setAuthCache(authCache);
211             }
212             if (this.log.isDebugEnabled()) {
213                 this.log.debug("Caching '" + authScheme.getSchemeName() +
214                         "' auth scheme for " + authhost);
215             }
216             authCache.put(authhost, authScheme);
217         }
218     }
219 
220     protected boolean isCachable(final AuthScheme authScheme) {
221         if (authScheme == null || !authScheme.isComplete()) {
222             return false;
223         }
224         final String schemeName = authScheme.getSchemeName();
225         return schemeName.equalsIgnoreCase(AuthSchemes.BASIC) ||
226                 schemeName.equalsIgnoreCase(AuthSchemes.DIGEST);
227     }
228 
229     public void authFailed(
230             final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
231         Args.notNull(authhost, "Host");
232         Args.notNull(context, "HTTP context");
233 
234         final HttpClientContext clientContext = HttpClientContext.adapt(context);
235 
236         final AuthCache authCache = clientContext.getAuthCache();
237         if (authCache != null) {
238             if (this.log.isDebugEnabled()) {
239                 this.log.debug("Clearing cached auth scheme for " + authhost);
240             }
241             authCache.remove(authhost);
242         }
243     }
244 
245 }