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.routing.RouteInfo;
47  import org.apache.http.protocol.HttpContext;
48  import org.apache.http.util.Args;
49  
50  /**
51   * Request interceptor that can preemptively authenticate against known hosts,
52   * if there is a cached {@link AuthScheme} instance in the local
53   * {@link AuthCache} associated with the given target or proxy host.
54   *
55   * @since 4.1
56   */
57  @Immutable
58  public class RequestAuthCache implements HttpRequestInterceptor {
59  
60      private final Log log = LogFactory.getLog(getClass());
61  
62      public RequestAuthCache() {
63          super();
64      }
65  
66      @Override
67      public void process(final HttpRequest request, final HttpContext context)
68              throws HttpException, IOException {
69          Args.notNull(request, "HTTP request");
70          Args.notNull(context, "HTTP context");
71  
72          final HttpClientContext clientContext = HttpClientContext.adapt(context);
73  
74          final AuthCache authCache = clientContext.getAuthCache();
75          if (authCache == null) {
76              this.log.debug("Auth cache not set in the context");
77              return;
78          }
79  
80          final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
81          if (credsProvider == null) {
82              this.log.debug("Credentials provider not set in the context");
83              return;
84          }
85  
86          final RouteInfo route = clientContext.getHttpRoute();
87          if (route == null) {
88              this.log.debug("Route info not set in the context");
89              return;
90          }
91  
92          HttpHost target = clientContext.getTargetHost();
93          if (target == null) {
94              this.log.debug("Target host not set in the context");
95              return;
96          }
97  
98          if (target.getPort() < 0) {
99              target = new HttpHost(
100                     target.getHostName(),
101                     route.getTargetHost().getPort(),
102                     target.getSchemeName());
103         }
104 
105         final AuthState targetState = clientContext.getTargetAuthState();
106         if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
107             final AuthScheme authScheme = authCache.get(target);
108             if (authScheme != null) {
109                 doPreemptiveAuth(target, authScheme, targetState, credsProvider);
110             }
111         }
112 
113         final HttpHost proxy = route.getProxyHost();
114         final AuthState proxyState = clientContext.getProxyAuthState();
115         if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
116             final AuthScheme authScheme = authCache.get(proxy);
117             if (authScheme != null) {
118                 doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
119             }
120         }
121     }
122 
123     private void doPreemptiveAuth(
124             final HttpHost host,
125             final AuthScheme authScheme,
126             final AuthState authState,
127             final CredentialsProvider credsProvider) {
128         final String schemeName = authScheme.getSchemeName();
129         if (this.log.isDebugEnabled()) {
130             this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
131         }
132 
133         final AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName);
134         final Credentials creds = credsProvider.getCredentials(authScope);
135 
136         if (creds != null) {
137             if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) {
138                 authState.setState(AuthProtocolState.CHALLENGED);
139             } else {
140                 authState.setState(AuthProtocolState.SUCCESS);
141             }
142             authState.update(authScheme, creds);
143         } else {
144             this.log.debug("No credentials for preemptive authentication");
145         }
146     }
147 
148 }