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  package org.apache.hc.client5.http.impl.auth;
28  
29  import java.net.Authenticator;
30  import java.net.MalformedURLException;
31  import java.net.PasswordAuthentication;
32  import java.net.URI;
33  import java.net.URISyntaxException;
34  import java.net.URL;
35  
36  import org.apache.hc.client5.http.auth.AuthScope;
37  import org.apache.hc.client5.http.auth.Credentials;
38  import org.apache.hc.client5.http.auth.CredentialsStore;
39  import org.apache.hc.client5.http.auth.StandardAuthScheme;
40  import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
41  import org.apache.hc.client5.http.protocol.HttpClientContext;
42  import org.apache.hc.core5.annotation.Contract;
43  import org.apache.hc.core5.annotation.ThreadingBehavior;
44  import org.apache.hc.core5.http.HttpRequest;
45  import org.apache.hc.core5.http.URIScheme;
46  import org.apache.hc.core5.http.protocol.HttpContext;
47  import org.apache.hc.core5.util.Args;
48  
49  /**
50   * Implementation of {@link CredentialsStore} backed by standard
51   * JRE {@link Authenticator}.
52   *
53   * @since 4.3
54   */
55  @Contract(threading = ThreadingBehavior.SAFE)
56  @SuppressWarnings("deprecation")
57  public class SystemDefaultCredentialsProvider implements CredentialsStore {
58  
59      private final BasicCredentialsProvider internal;
60  
61      /**
62       * Default constructor.
63       */
64      public SystemDefaultCredentialsProvider() {
65          super();
66          this.internal = new BasicCredentialsProvider();
67      }
68  
69      @Override
70      public void setCredentials(final AuthScope authScope, final Credentials credentials) {
71          internal.setCredentials(authScope, credentials);
72      }
73  
74      private static PasswordAuthentication getSystemCreds(
75              final String protocol,
76              final AuthScope authScope,
77              final Authenticator.RequestorType requestorType,
78              final HttpClientContext context) {
79          final HttpRequest request = context != null ? context.getRequest() : null;
80          URL targetHostURL;
81          try {
82              final URI uri = request != null ? request.getUri() : null;
83              targetHostURL = uri != null ? uri.toURL() : null;
84          } catch (final URISyntaxException | MalformedURLException ignore) {
85              targetHostURL = null;
86          }
87          // use null addr, because the authentication fails if it does not exactly match the expected realm's host
88          return Authenticator.requestPasswordAuthentication(
89                  authScope.getHost(),
90                  null,
91                  authScope.getPort(),
92                  protocol,
93                  authScope.getRealm(),
94                  authScope.getSchemeName(),
95                  targetHostURL,
96                  requestorType);
97      }
98  
99      @Override
100     public Credentials getCredentials(final AuthScope authScope, final HttpContext context) {
101         Args.notNull(authScope, "Auth scope");
102         final Credentials localcreds = internal.getCredentials(authScope, context);
103         if (localcreds != null) {
104             return localcreds;
105         }
106         final String host = authScope.getHost();
107         if (host != null) {
108             final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : null;
109             final String protocol = authScope.getProtocol() != null ? authScope.getProtocol() : (authScope.getPort() == 443 ? URIScheme.HTTPS.id : URIScheme.HTTP.id);
110             PasswordAuthentication systemcreds = getSystemCreds(
111                     protocol, authScope, Authenticator.RequestorType.SERVER, clientContext);
112             if (systemcreds == null) {
113                 systemcreds = getSystemCreds(
114                         protocol, authScope, Authenticator.RequestorType.PROXY, clientContext);
115             }
116             if (systemcreds == null) {
117                 // Look for values given using http.proxyUser/http.proxyPassword or
118                 // https.proxyUser/https.proxyPassword. We cannot simply use the protocol from
119                 // the origin since a proxy retrieved from https.proxyHost/https.proxyPort will
120                 // still use http as protocol
121                 systemcreds = getProxyCredentials(URIScheme.HTTP.getId(), authScope);
122                 if (systemcreds == null) {
123                     systemcreds = getProxyCredentials(URIScheme.HTTPS.getId(), authScope);
124                 }
125             }
126             if (systemcreds != null) {
127                 final String domain = System.getProperty("http.auth.ntlm.domain");
128                 if (domain != null) {
129                     return new org.apache.hc.client5.http.auth.NTCredentials(
130                             systemcreds.getUserName(), systemcreds.getPassword(), null, domain);
131                 }
132                 if (StandardAuthScheme.NTLM.equalsIgnoreCase(authScope.getSchemeName())) {
133                     // Domain may be specified in a fully qualified user name
134                     return new org.apache.hc.client5.http.auth.NTCredentials(
135                             systemcreds.getUserName(), systemcreds.getPassword(), null, null);
136                 }
137                 return new UsernamePasswordCredentials(systemcreds.getUserName(), systemcreds.getPassword());
138             }
139         }
140         return null;
141     }
142 
143     private static PasswordAuthentication getProxyCredentials(final String protocol, final AuthScope authScope) {
144         final String proxyHost = System.getProperty(protocol + ".proxyHost");
145         if (proxyHost == null) {
146             return null;
147         }
148         final String proxyPort = System.getProperty(protocol + ".proxyPort");
149         if (proxyPort == null) {
150             return null;
151         }
152 
153         try {
154             final AuthScope systemScope = new AuthScope(proxyHost, Integer.parseInt(proxyPort));
155             if (authScope.match(systemScope) >= 0) {
156                 final String proxyUser = System.getProperty(protocol + ".proxyUser");
157                 if (proxyUser == null) {
158                     return null;
159                 }
160                 final String proxyPassword = System.getProperty(protocol + ".proxyPassword");
161 
162                 return new PasswordAuthentication(proxyUser,
163                         proxyPassword != null ? proxyPassword.toCharArray() : new char[] {});
164             }
165         } catch (final NumberFormatException ex) {
166         }
167 
168         return null;
169     }
170 
171     @Override
172     public void clear() {
173         internal.clear();
174     }
175 
176 }