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.client.protocol;
29  
30  import java.io.IOException;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.http.HttpException;
35  import org.apache.http.HttpHost;
36  import org.apache.http.HttpRequest;
37  import org.apache.http.HttpRequestInterceptor;
38  import org.apache.http.annotation.Immutable;
39  import org.apache.http.auth.AuthProtocolState;
40  import org.apache.http.auth.AuthScheme;
41  import org.apache.http.auth.AuthScope;
42  import org.apache.http.auth.AuthState;
43  import org.apache.http.auth.Credentials;
44  import org.apache.http.client.AuthCache;
45  import org.apache.http.client.CredentialsProvider;
46  import org.apache.http.conn.scheme.Scheme;
47  import org.apache.http.conn.scheme.SchemeRegistry;
48  import org.apache.http.protocol.ExecutionContext;
49  import org.apache.http.protocol.HttpContext;
50  
51  /**
52   * Request interceptor that can preemptively authenticate against known hosts,
53   * if there is a cached {@link AuthScheme} instance in the local
54   * {@link AuthCache} associated with the given target or proxy host.
55   *
56   * @since 4.1
57   */
58  @Immutable
59  public class RequestAuthCache implements HttpRequestInterceptor {
60  
61      private final Log log = LogFactory.getLog(getClass());
62  
63      public RequestAuthCache() {
64          super();
65      }
66  
67      public void process(final HttpRequest request, final HttpContext context)
68              throws HttpException, IOException {
69          if (request == null) {
70              throw new IllegalArgumentException("HTTP request may not be null");
71          }
72          if (context == null) {
73              throw new IllegalArgumentException("HTTP context may not be null");
74          }
75  
76          AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
77          if (authCache == null) {
78              this.log.debug("Auth cache not set in the context");
79              return;
80          }
81  
82          CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
83                  ClientContext.CREDS_PROVIDER);
84          if (credsProvider == null) {
85              this.log.debug("Credentials provider not set in the context");
86              return;
87          }
88  
89          HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
90          if (target.getPort() < 0) {
91              SchemeRegistry schemeRegistry = (SchemeRegistry) context.getAttribute(
92                      ClientContext.SCHEME_REGISTRY);
93              Scheme scheme = schemeRegistry.getScheme(target);
94              target = new HttpHost(target.getHostName(),
95                      scheme.resolvePort(target.getPort()), target.getSchemeName());
96          }
97  
98          AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
99          if (target != null && targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
100             AuthScheme authScheme = authCache.get(target);
101             if (authScheme != null) {
102                 doPreemptiveAuth(target, authScheme, targetState, credsProvider);
103             }
104         }
105 
106         HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
107         AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
108         if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
109             AuthScheme authScheme = authCache.get(proxy);
110             if (authScheme != null) {
111                 doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
112             }
113         }
114     }
115 
116     private void doPreemptiveAuth(
117             final HttpHost host,
118             final AuthScheme authScheme,
119             final AuthState authState,
120             final CredentialsProvider credsProvider) {
121         String schemeName = authScheme.getSchemeName();
122         if (this.log.isDebugEnabled()) {
123             this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
124         }
125 
126         AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName);
127         Credentials creds = credsProvider.getCredentials(authScope);
128 
129         if (creds != null) {
130             if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) {
131                 authState.setState(AuthProtocolState.CHALLENGED);
132             } else {
133                 authState.setState(AuthProtocolState.SUCCESS);
134             }
135             authState.update(authScheme, creds);
136         } else {
137             this.log.debug("No credentials for preemptive authentication");
138         }
139     }
140 
141 }