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.hc.client5.http.protocol;
29  
30  import java.io.IOException;
31  
32  import org.apache.hc.client5.http.RouteInfo;
33  import org.apache.hc.client5.http.auth.AuthCache;
34  import org.apache.hc.client5.http.auth.AuthExchange;
35  import org.apache.hc.client5.http.auth.AuthScheme;
36  import org.apache.hc.client5.http.auth.CredentialsProvider;
37  import org.apache.hc.core5.annotation.Contract;
38  import org.apache.hc.core5.annotation.ThreadingBehavior;
39  import org.apache.hc.core5.http.EntityDetails;
40  import org.apache.hc.core5.http.HttpException;
41  import org.apache.hc.core5.http.HttpHost;
42  import org.apache.hc.core5.http.HttpRequest;
43  import org.apache.hc.core5.http.HttpRequestInterceptor;
44  import org.apache.hc.core5.http.protocol.HttpContext;
45  import org.apache.hc.core5.net.URIAuthority;
46  import org.apache.hc.core5.util.Args;
47  import org.slf4j.Logger;
48  import org.slf4j.LoggerFactory;
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  @Contract(threading = ThreadingBehavior.STATELESS)
58  public class RequestAuthCache implements HttpRequestInterceptor {
59  
60      private static final Logger LOG = LoggerFactory.getLogger(RequestAuthCache.class);
61  
62      public RequestAuthCache() {
63          super();
64      }
65  
66      @Override
67      public void process(final HttpRequest request, final EntityDetails entity, 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              LOG.debug("Auth cache not set in the context");
77              return;
78          }
79  
80          final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
81          if (credsProvider == null) {
82              LOG.debug("Credentials provider not set in the context");
83              return;
84          }
85  
86          final RouteInfo route = clientContext.getHttpRoute();
87          if (route == null) {
88              LOG.debug("Route info not set in the context");
89              return;
90          }
91  
92          final URIAuthority authority = request.getAuthority();
93          final HttpHost target;
94          if (authority != null) {
95              target = new HttpHost(
96                      request.getScheme(),
97                      authority.getHostName(),
98                      authority.getPort() >= 0 ? authority.getPort() : route.getTargetHost().getPort());
99          } else {
100             target = route.getTargetHost();
101         }
102         final AuthExchange targetAuthExchange = clientContext.getAuthExchange(target);
103         if (targetAuthExchange.getState() == AuthExchange.State.UNCHALLENGED) {
104             final AuthScheme authScheme = authCache.get(target);
105             if (authScheme != null) {
106                 if (LOG.isDebugEnabled()) {
107                     LOG.debug("Re-using cached '{}' auth scheme for {}", authScheme.getName(), target);
108                 }
109                 targetAuthExchange.select(authScheme);
110             }
111         }
112 
113         final HttpHost proxy = route.getProxyHost();
114         if (proxy != null) {
115             final AuthExchange proxyAuthExchange = clientContext.getAuthExchange(proxy);
116             if (proxyAuthExchange.getState() == AuthExchange.State.UNCHALLENGED) {
117                 final AuthScheme authScheme = authCache.get(proxy);
118                 if (authScheme != null) {
119                     if (LOG.isDebugEnabled()) {
120                         LOG.debug("Re-using cached '{}' auth scheme for {}", authScheme.getName(), proxy);
121                     }
122                     proxyAuthExchange.select(authScheme);
123                 }
124             }
125         }
126     }
127 
128 }