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.NTCredentials;
40  import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
41  import org.apache.hc.client5.http.auth.StandardAuthScheme;
42  import org.apache.hc.client5.http.protocol.HttpClientContext;
43  import org.apache.hc.core5.annotation.Contract;
44  import org.apache.hc.core5.annotation.ThreadingBehavior;
45  import org.apache.hc.core5.http.HttpRequest;
46  import org.apache.hc.core5.http.URIScheme;
47  import org.apache.hc.core5.http.protocol.HttpContext;
48  import org.apache.hc.core5.util.Args;
49  
50  /**
51   * Implementation of {@link CredentialsStore} backed by standard
52   * JRE {@link Authenticator}.
53   *
54   * @since 4.3
55   */
56  @Contract(threading = ThreadingBehavior.SAFE)
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 NTCredentials(systemcreds.getUserName(), systemcreds.getPassword(), null, domain);
130                 }
131                 if (StandardAuthScheme.NTLM.equalsIgnoreCase(authScope.getSchemeName())) {
132                     // Domain may be specified in a fully qualified user name
133                     return new NTCredentials(
134                             systemcreds.getUserName(), systemcreds.getPassword(), null, null);
135                 }
136                 return new UsernamePasswordCredentials(systemcreds.getUserName(), systemcreds.getPassword());
137             }
138         }
139         return null;
140     }
141 
142     private static PasswordAuthentication getProxyCredentials(final String protocol, final AuthScope authScope) {
143         final String proxyHost = System.getProperty(protocol + ".proxyHost");
144         if (proxyHost == null) {
145             return null;
146         }
147         final String proxyPort = System.getProperty(protocol + ".proxyPort");
148         if (proxyPort == null) {
149             return null;
150         }
151 
152         try {
153             final AuthScope systemScope = new AuthScope(proxyHost, Integer.parseInt(proxyPort));
154             if (authScope.match(systemScope) >= 0) {
155                 final String proxyUser = System.getProperty(protocol + ".proxyUser");
156                 if (proxyUser == null) {
157                     return null;
158                 }
159                 final String proxyPassword = System.getProperty(protocol + ".proxyPassword");
160 
161                 return new PasswordAuthentication(proxyUser,
162                         proxyPassword != null ? proxyPassword.toCharArray() : new char[] {});
163             }
164         } catch (final NumberFormatException ex) {
165         }
166 
167         return null;
168     }
169 
170     @Override
171     public void clear() {
172         internal.clear();
173     }
174 
175 }