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.Contract;
39  import org.apache.http.annotation.ThreadingBehavior;
40  import org.apache.http.auth.AuthProtocolState;
41  import org.apache.http.auth.AuthScheme;
42  import org.apache.http.auth.AuthScope;
43  import org.apache.http.auth.AuthState;
44  import org.apache.http.auth.Credentials;
45  import org.apache.http.client.AuthCache;
46  import org.apache.http.client.CredentialsProvider;
47  import org.apache.http.conn.routing.RouteInfo;
48  import org.apache.http.protocol.HttpContext;
49  import org.apache.http.util.Args;
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  @Contract(threading = ThreadingBehavior.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      @Override
68      public void process(final HttpRequest request, final HttpContext context)
69              throws HttpException, IOException {
70          Args.notNull(request, "HTTP request");
71          Args.notNull(context, "HTTP context");
72  
73          final HttpClientContext clientContext = HttpClientContext.adapt(context);
74  
75          final AuthCache authCache = clientContext.getAuthCache();
76          if (authCache == null) {
77              this.log.debug("Auth cache not set in the context");
78              return;
79          }
80  
81          final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
82          if (credsProvider == null) {
83              this.log.debug("Credentials provider not set in the context");
84              return;
85          }
86  
87          final RouteInfo route = clientContext.getHttpRoute();
88          if (route == null) {
89              this.log.debug("Route info not set in the context");
90              return;
91          }
92  
93          HttpHost target = clientContext.getTargetHost();
94          if (target == null) {
95              this.log.debug("Target host not set in the context");
96              return;
97          }
98  
99          if (target.getPort() < 0) {
100             target = new HttpHost(
101                     target.getHostName(),
102                     route.getTargetHost().getPort(),
103                     target.getSchemeName());
104         }
105 
106         final AuthState targetState = clientContext.getTargetAuthState();
107         if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
108             final AuthScheme authScheme = authCache.get(target);
109             if (authScheme != null) {
110                 doPreemptiveAuth(target, authScheme, targetState, credsProvider);
111             }
112         }
113 
114         final HttpHost proxy = route.getProxyHost();
115         final AuthState proxyState = clientContext.getProxyAuthState();
116         if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
117             final AuthScheme authScheme = authCache.get(proxy);
118             if (authScheme != null) {
119                 doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
120             }
121         }
122     }
123 
124     private void doPreemptiveAuth(
125             final HttpHost host,
126             final AuthScheme authScheme,
127             final AuthState authState,
128             final CredentialsProvider credsProvider) {
129         final String schemeName = authScheme.getSchemeName();
130         if (this.log.isDebugEnabled()) {
131             this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
132         }
133 
134         final AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName);
135         final Credentials creds = credsProvider.getCredentials(authScope);
136 
137         if (creds != null) {
138             if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) {
139                 authState.setState(AuthProtocolState.CHALLENGED);
140             } else {
141                 authState.setState(AuthProtocolState.SUCCESS);
142             }
143             authState.update(authScheme, creds);
144         } else {
145             this.log.debug("No credentials for preemptive authentication");
146         }
147     }
148 
149 }