jdk/src/java.httpclient/share/classes/java/net/http/AuthenticationFilter.java
changeset 42483 3850c235c3fb
parent 42482 15297dde0d55
parent 42479 a80dbf731cbe
child 42489 a9e4de33da2e
equal deleted inserted replaced
42482:15297dde0d55 42483:3850c235c3fb
     1 /*
       
     2  * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package java.net.http;
       
    27 
       
    28 import java.io.IOException;
       
    29 import static java.net.Authenticator.RequestorType.PROXY;
       
    30 import static java.net.Authenticator.RequestorType.SERVER;
       
    31 import java.net.PasswordAuthentication;
       
    32 import java.net.URI;
       
    33 import java.net.InetSocketAddress;
       
    34 import java.net.URISyntaxException;
       
    35 import java.util.Base64;
       
    36 import java.util.HashMap;
       
    37 import java.util.LinkedList;
       
    38 import static java.nio.charset.StandardCharsets.ISO_8859_1;
       
    39 
       
    40 /**
       
    41  * Implementation of Http Basic authentication.
       
    42  */
       
    43 class AuthenticationFilter implements HeaderFilter {
       
    44 
       
    45     static private final Base64.Encoder encoder = Base64.getEncoder();
       
    46 
       
    47     static final int DEFAULT_RETRY_LIMIT = 3;
       
    48 
       
    49     static final int retry_limit = Utils.getIntegerNetProperty(
       
    50             "java.net.httpclient.auth.retrylimit", DEFAULT_RETRY_LIMIT);
       
    51 
       
    52     static final int UNAUTHORIZED = 401;
       
    53     static final int PROXY_UNAUTHORIZED = 407;
       
    54 
       
    55     private PasswordAuthentication getCredentials(String header,
       
    56                                                   boolean proxy,
       
    57                                                   HttpRequestImpl req)
       
    58         throws IOException
       
    59     {
       
    60         HttpClientImpl client = req.client();
       
    61         java.net.Authenticator auth =
       
    62                 client.authenticator()
       
    63                       .orElseThrow(() -> new IOException("No authenticator set"));
       
    64         URI uri = req.uri();
       
    65         HeaderParser parser = new HeaderParser(header);
       
    66         String authscheme = parser.findKey(0);
       
    67 
       
    68         String realm = parser.findValue("realm");
       
    69         java.net.Authenticator.RequestorType rtype = proxy ? PROXY : SERVER;
       
    70 
       
    71         // needs to be instance method in Authenticator
       
    72         return auth.requestPasswordAuthenticationInstance(uri.getHost(),
       
    73                                                           null,
       
    74                                                           uri.getPort(),
       
    75                                                           uri.getScheme(),
       
    76                                                           realm,
       
    77                                                           authscheme,
       
    78                                                           uri.toURL(),
       
    79                                                           rtype
       
    80         );
       
    81     }
       
    82 
       
    83     private URI getProxyURI(HttpRequestImpl r) {
       
    84         InetSocketAddress proxy = r.proxy();
       
    85         if (proxy == null) {
       
    86             return null;
       
    87         }
       
    88 
       
    89         // our own private scheme for proxy URLs
       
    90         // eg. proxy.http://host:port/
       
    91         String scheme = "proxy." + r.uri().getScheme();
       
    92         try {
       
    93             return new URI(scheme,
       
    94                            null,
       
    95                            proxy.getHostString(),
       
    96                            proxy.getPort(),
       
    97                            null,
       
    98                            null,
       
    99                            null);
       
   100         } catch (URISyntaxException e) {
       
   101             throw new InternalError(e);
       
   102         }
       
   103     }
       
   104 
       
   105     @Override
       
   106     public void request(HttpRequestImpl r) throws IOException {
       
   107         // use preemptive authentication if an entry exists.
       
   108         Cache cache = getCache(r);
       
   109 
       
   110         // Proxy
       
   111         if (r.exchange.proxyauth == null) {
       
   112             URI proxyURI = getProxyURI(r);
       
   113             if (proxyURI != null) {
       
   114                 CacheEntry ca = cache.get(proxyURI, true);
       
   115                 if (ca != null) {
       
   116                     r.exchange.proxyauth = new AuthInfo(true, ca.scheme, null, ca);
       
   117                     addBasicCredentials(r, true, ca.value);
       
   118                 }
       
   119             }
       
   120         }
       
   121 
       
   122         // Server
       
   123         if (r.exchange.serverauth == null) {
       
   124             CacheEntry ca = cache.get(r.uri(), false);
       
   125             if (ca != null) {
       
   126                 r.exchange.serverauth = new AuthInfo(true, ca.scheme, null, ca);
       
   127                 addBasicCredentials(r, false, ca.value);
       
   128             }
       
   129         }
       
   130     }
       
   131 
       
   132     // TODO: refactor into per auth scheme class
       
   133     static private void addBasicCredentials(HttpRequestImpl r,
       
   134                                             boolean proxy,
       
   135                                             PasswordAuthentication pw) {
       
   136         String hdrname = proxy ? "Proxy-Authorization" : "Authorization";
       
   137         StringBuilder sb = new StringBuilder(128);
       
   138         sb.append(pw.getUserName()).append(':').append(pw.getPassword());
       
   139         String s = encoder.encodeToString(sb.toString().getBytes(ISO_8859_1));
       
   140         String value = "Basic " + s;
       
   141         r.setSystemHeader(hdrname, value);
       
   142     }
       
   143 
       
   144     // Information attached to a HttpRequestImpl relating to authentication
       
   145     static class AuthInfo {
       
   146         final boolean fromcache;
       
   147         final String scheme;
       
   148         int retries;
       
   149         PasswordAuthentication credentials; // used in request
       
   150         CacheEntry cacheEntry; // if used
       
   151 
       
   152         AuthInfo(boolean fromcache,
       
   153                  String scheme,
       
   154                  PasswordAuthentication credentials) {
       
   155             this.fromcache = fromcache;
       
   156             this.scheme = scheme;
       
   157             this.credentials = credentials;
       
   158             this.retries = 1;
       
   159         }
       
   160 
       
   161         AuthInfo(boolean fromcache,
       
   162                  String scheme,
       
   163                  PasswordAuthentication credentials,
       
   164                  CacheEntry ca) {
       
   165             this(fromcache, scheme, credentials);
       
   166             assert credentials == null || (ca != null && ca.value == null);
       
   167             cacheEntry = ca;
       
   168         }
       
   169     }
       
   170 
       
   171     @Override
       
   172     public HttpRequestImpl response(HttpResponseImpl r) throws IOException {
       
   173         Cache cache = getCache(r.request);
       
   174         int status = r.statusCode();
       
   175         HttpHeaders hdrs = r.headers();
       
   176         HttpRequestImpl req = r.request();
       
   177 
       
   178         if (status != UNAUTHORIZED && status != PROXY_UNAUTHORIZED) {
       
   179             // check if any authentication succeeded for first time
       
   180             if (req.exchange.serverauth != null && !req.exchange.serverauth.fromcache) {
       
   181                 AuthInfo au = req.exchange.serverauth;
       
   182                 cache.store(au.scheme, req.uri(), false, au.credentials);
       
   183             }
       
   184             if (req.exchange.proxyauth != null && !req.exchange.proxyauth.fromcache) {
       
   185                 AuthInfo au = req.exchange.proxyauth;
       
   186                 cache.store(au.scheme, req.uri(), false, au.credentials);
       
   187             }
       
   188             return null;
       
   189         }
       
   190 
       
   191         boolean proxy = status == PROXY_UNAUTHORIZED;
       
   192         String authname = proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
       
   193         String authval = hdrs.firstValue(authname).orElseThrow(() -> {
       
   194             return new IOException("Invalid auth header");
       
   195         });
       
   196         HeaderParser parser = new HeaderParser(authval);
       
   197         String scheme = parser.findKey(0);
       
   198 
       
   199         // TODO: Need to generalise from Basic only. Delegate to a provider class etc.
       
   200 
       
   201         if (!scheme.equalsIgnoreCase("Basic")) {
       
   202             return null;   // error gets returned to app
       
   203         }
       
   204 
       
   205         String realm = parser.findValue("realm");
       
   206         AuthInfo au = proxy ? req.exchange.proxyauth : req.exchange.serverauth;
       
   207         if (au == null) {
       
   208             PasswordAuthentication pw = getCredentials(authval, proxy, req);
       
   209             if (pw == null) {
       
   210                 throw new IOException("No credentials provided");
       
   211             }
       
   212             // No authentication in request. Get credentials from user
       
   213             au = new AuthInfo(false, "Basic", pw);
       
   214             if (proxy)
       
   215                 req.exchange.proxyauth = au;
       
   216             else
       
   217                 req.exchange.serverauth = au;
       
   218             addBasicCredentials(req, proxy, pw);
       
   219             return req;
       
   220         } else if (au.retries > retry_limit) {
       
   221             throw new IOException("too many authentication attempts");
       
   222         } else {
       
   223             // we sent credentials, but they were rejected
       
   224             if (au.fromcache) {
       
   225                 cache.remove(au.cacheEntry);
       
   226             }
       
   227             // try again
       
   228             au.credentials = getCredentials(authval, proxy, req);
       
   229             addBasicCredentials(req, proxy, au.credentials);
       
   230             au.retries++;
       
   231             return req;
       
   232         }
       
   233     }
       
   234 
       
   235     static final HashMap<HttpClientImpl,Cache> caches = new HashMap<>();
       
   236 
       
   237     static synchronized Cache getCache(HttpRequestImpl req) {
       
   238         HttpClientImpl client = req.client();
       
   239         Cache c = caches.get(client);
       
   240         if (c == null) {
       
   241             c = new Cache();
       
   242             caches.put(client, c);
       
   243         }
       
   244         return c;
       
   245     }
       
   246 
       
   247     static class Cache {
       
   248         final LinkedList<CacheEntry> entries = new LinkedList<>();
       
   249 
       
   250         synchronized CacheEntry get(URI uri, boolean proxy) {
       
   251             for (CacheEntry entry : entries) {
       
   252                 if (entry.equalsKey(uri, proxy)) {
       
   253                     return entry;
       
   254                 }
       
   255             }
       
   256             return null;
       
   257         }
       
   258 
       
   259         synchronized void remove(String authscheme, URI domain, boolean proxy) {
       
   260             for (CacheEntry entry : entries) {
       
   261                 if (entry.equalsKey(domain, proxy)) {
       
   262                     entries.remove(entry);
       
   263                 }
       
   264             }
       
   265         }
       
   266 
       
   267         synchronized void remove(CacheEntry entry) {
       
   268             entries.remove(entry);
       
   269         }
       
   270 
       
   271         synchronized void store(String authscheme,
       
   272                                 URI domain,
       
   273                                 boolean proxy,
       
   274                                 PasswordAuthentication value) {
       
   275             remove(authscheme, domain, proxy);
       
   276             entries.add(new CacheEntry(authscheme, domain, proxy, value));
       
   277         }
       
   278     }
       
   279 
       
   280     static class CacheEntry {
       
   281         final String root;
       
   282         final String scheme;
       
   283         final boolean proxy;
       
   284         final PasswordAuthentication value;
       
   285 
       
   286         CacheEntry(String authscheme,
       
   287                    URI uri,
       
   288                    boolean proxy,
       
   289                    PasswordAuthentication value) {
       
   290             this.scheme = authscheme;
       
   291             this.root = uri.resolve(".").toString(); // remove extraneous components
       
   292             this.proxy = proxy;
       
   293             this.value = value;
       
   294         }
       
   295 
       
   296         public PasswordAuthentication value() {
       
   297             return value;
       
   298         }
       
   299 
       
   300         public boolean equalsKey(URI uri, boolean proxy) {
       
   301             if (this.proxy != proxy) {
       
   302                 return false;
       
   303             }
       
   304             String other = uri.toString();
       
   305             return other.startsWith(root);
       
   306         }
       
   307     }
       
   308 }