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.List;
35  import java.util.Locale;
36  import java.util.Map;
37  
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.apache.http.FormattedHeader;
41  import org.apache.http.Header;
42  import org.apache.http.HttpResponse;
43  import org.apache.http.annotation.Contract;
44  import org.apache.http.annotation.ThreadingBehavior;
45  import org.apache.http.auth.AuthScheme;
46  import org.apache.http.auth.AuthSchemeRegistry;
47  import org.apache.http.auth.AuthenticationException;
48  import org.apache.http.auth.MalformedChallengeException;
49  import org.apache.http.client.AuthenticationHandler;
50  import org.apache.http.client.params.AuthPolicy;
51  import org.apache.http.client.protocol.ClientContext;
52  import org.apache.http.protocol.HTTP;
53  import org.apache.http.protocol.HttpContext;
54  import org.apache.http.util.Asserts;
55  import org.apache.http.util.CharArrayBuffer;
56  
57  /**
58   * Base class for {@link AuthenticationHandler} implementations.
59   *
60   * @since 4.0
61   *
62   * @deprecated (4.2)  use {@link org.apache.http.client.AuthenticationStrategy}
63   */
64  @Deprecated
65  @Contract(threading = ThreadingBehavior.IMMUTABLE)
66  public abstract class AbstractAuthenticationHandler implements AuthenticationHandler {
67  
68      private final Log log = LogFactory.getLog(getClass());
69  
70      private static final List<String> DEFAULT_SCHEME_PRIORITY =
71          Collections.unmodifiableList(Arrays.asList(new String[] {
72                  AuthPolicy.SPNEGO,
73                  AuthPolicy.NTLM,
74                  AuthPolicy.DIGEST,
75                  AuthPolicy.BASIC
76      }));
77  
78      public AbstractAuthenticationHandler() {
79          super();
80      }
81  
82      protected Map<String, Header> parseChallenges(
83              final Header[] headers) throws MalformedChallengeException {
84  
85          final Map<String, Header> map = new HashMap<String, Header>(headers.length);
86          for (final Header header : headers) {
87              final CharArrayBuffer buffer;
88              int pos;
89              if (header instanceof FormattedHeader) {
90                  buffer = ((FormattedHeader) header).getBuffer();
91                  pos = ((FormattedHeader) header).getValuePos();
92              } else {
93                  final String s = header.getValue();
94                  if (s == null) {
95                      throw new MalformedChallengeException("Header value is null");
96                  }
97                  buffer = new CharArrayBuffer(s.length());
98                  buffer.append(s);
99                  pos = 0;
100             }
101             while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
102                 pos++;
103             }
104             final int beginIndex = pos;
105             while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
106                 pos++;
107             }
108             final int endIndex = pos;
109             final String s = buffer.substring(beginIndex, endIndex);
110             map.put(s.toLowerCase(Locale.ROOT), header);
111         }
112         return map;
113     }
114 
115     /**
116      * Returns default list of auth scheme names in their order of preference.
117      *
118      * @return list of auth scheme names
119      */
120     protected List<String> getAuthPreferences() {
121         return DEFAULT_SCHEME_PRIORITY;
122     }
123 
124     /**
125      * Returns default list of auth scheme names in their order of preference
126      * based on the HTTP response and the current execution context.
127      *
128      * @param response HTTP response.
129      * @param context HTTP execution context.
130      *
131      * @since 4.1
132      */
133     protected List<String> getAuthPreferences(
134             final HttpResponse response,
135             final HttpContext context) {
136         return getAuthPreferences();
137     }
138 
139     @Override
140     public AuthScheme selectScheme(
141             final Map<String, Header> challenges,
142             final HttpResponse response,
143             final HttpContext context) throws AuthenticationException {
144 
145         final AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute(
146                 ClientContext.AUTHSCHEME_REGISTRY);
147         Asserts.notNull(registry, "AuthScheme registry");
148         Collection<String> authPrefs = getAuthPreferences(response, context);
149         if (authPrefs == null) {
150             authPrefs = DEFAULT_SCHEME_PRIORITY;
151         }
152 
153         if (this.log.isDebugEnabled()) {
154             this.log.debug("Authentication schemes in the order of preference: "
155                 + authPrefs);
156         }
157 
158         AuthScheme authScheme = null;
159         for (final String id: authPrefs) {
160             final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
161 
162             if (challenge != null) {
163                 if (this.log.isDebugEnabled()) {
164                     this.log.debug(id + " authentication scheme selected");
165                 }
166                 try {
167                     authScheme = registry.getAuthScheme(id, response.getParams());
168                     break;
169                 } catch (final IllegalStateException e) {
170                     if (this.log.isWarnEnabled()) {
171                         this.log.warn("Authentication scheme " + id + " not supported");
172                         // Try again
173                     }
174                 }
175             } else {
176                 if (this.log.isDebugEnabled()) {
177                     this.log.debug("Challenge for " + id + " authentication scheme not available");
178                     // Try again
179                 }
180             }
181         }
182         if (authScheme == null) {
183             // If none selected, something is wrong
184             throw new AuthenticationException(
185                 "Unable to respond to any of these challenges: "
186                     + challenges);
187         }
188         return authScheme;
189     }
190 
191 }