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