jdk/src/java.httpclient/share/classes/java/net/http/AuthenticationFilter.java
changeset 36131 379db4b2f95d
child 37720 45cd7cc65382
equal deleted inserted replaced
36130:5423259ef9ea 36131:379db4b2f95d
       
     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  */
       
    24 package java.net.http;
       
    25 
       
    26 import java.io.IOException;
       
    27 import static java.net.Authenticator.RequestorType.PROXY;
       
    28 import static java.net.Authenticator.RequestorType.SERVER;
       
    29 import java.net.PasswordAuthentication;
       
    30 import java.net.URI;
       
    31 import java.net.InetSocketAddress;
       
    32 import java.net.URISyntaxException;
       
    33 import java.util.Base64;
       
    34 import java.util.HashMap;
       
    35 import java.util.LinkedList;
       
    36 import static java.nio.charset.StandardCharsets.ISO_8859_1;
       
    37 
       
    38 /**
       
    39  * Implementation of Http Basic authentication.
       
    40  */
       
    41 class AuthenticationFilter implements HeaderFilter {
       
    42 
       
    43     static private final Base64.Encoder encoder = Base64.getEncoder();
       
    44 
       
    45     static final int DEFAULT_RETRY_LIMIT = 3;
       
    46 
       
    47     static final int retry_limit = Utils.getIntegerNetProperty(
       
    48             "sun.net.httpclient.auth.retrylimit", DEFAULT_RETRY_LIMIT);
       
    49 
       
    50     static final int UNAUTHORIZED = 401;
       
    51     static final int PROXY_UNAUTHORIZED = 407;
       
    52 
       
    53     private PasswordAuthentication getCredentials(String header,
       
    54                                                   boolean proxy,
       
    55                                                   HttpRequestImpl req)
       
    56         throws IOException
       
    57     {
       
    58         HttpClientImpl client = req.client();
       
    59         java.net.Authenticator auth =
       
    60                 client.authenticator()
       
    61                       .orElseThrow(() -> new IOException("No authenticator set"));
       
    62         URI uri = req.uri();
       
    63         HeaderParser parser = new HeaderParser(header);
       
    64         String authscheme = parser.findKey(0);
       
    65 
       
    66         String realm = parser.findValue("realm");
       
    67         java.net.Authenticator.RequestorType rtype = proxy ? PROXY : SERVER;
       
    68 
       
    69         // needs to be instance method in Authenticator
       
    70         return auth.requestPasswordAuthenticationInstance(uri.getHost(),
       
    71                                                           null,
       
    72                                                           uri.getPort(),
       
    73                                                           uri.getScheme(),
       
    74                                                           realm,
       
    75                                                           authscheme,
       
    76                                                           uri.toURL(),
       
    77                                                           rtype
       
    78         );
       
    79     }
       
    80 
       
    81     private URI getProxyURI(HttpRequestImpl r) {
       
    82         InetSocketAddress proxy = r.proxy();
       
    83         if (proxy == null) {
       
    84             return null;
       
    85         }
       
    86 
       
    87         // our own private scheme for proxy URLs
       
    88         // eg. proxy.http://host:port/
       
    89         String scheme = "proxy." + r.uri().getScheme();
       
    90         try {
       
    91             return new URI(scheme,
       
    92                            null,
       
    93                            proxy.getHostString(),
       
    94                            proxy.getPort(),
       
    95                            null,
       
    96                            null,
       
    97                            null);
       
    98         } catch (URISyntaxException e) {
       
    99             throw new InternalError(e);
       
   100         }
       
   101     }
       
   102 
       
   103     @Override
       
   104     public void request(HttpRequestImpl r) throws IOException {
       
   105         // use preemptive authentication if an entry exists.
       
   106         Cache cache = getCache(r);
       
   107 
       
   108         // Proxy
       
   109         if (r.exchange.proxyauth == null) {
       
   110             URI proxyURI = getProxyURI(r);
       
   111             if (proxyURI != null) {
       
   112                 CacheEntry ca = cache.get(proxyURI, true);
       
   113                 if (ca != null) {
       
   114                     r.exchange.proxyauth = new AuthInfo(true, ca.scheme, null, ca);
       
   115                     addBasicCredentials(r, true, ca.value);
       
   116                 }
       
   117             }
       
   118         }
       
   119 
       
   120         // Server
       
   121         if (r.exchange.serverauth == null) {
       
   122             CacheEntry ca = cache.get(r.uri(), false);
       
   123             if (ca != null) {
       
   124                 r.exchange.serverauth = new AuthInfo(true, ca.scheme, null, ca);
       
   125                 addBasicCredentials(r, false, ca.value);
       
   126             }
       
   127         }
       
   128     }
       
   129 
       
   130     // TODO: refactor into per auth scheme class
       
   131     static private void addBasicCredentials(HttpRequestImpl r,
       
   132                                             boolean proxy,
       
   133                                             PasswordAuthentication pw) {
       
   134         String hdrname = proxy ? "Proxy-Authorization" : "Authorization";
       
   135         StringBuilder sb = new StringBuilder(128);
       
   136         sb.append(pw.getUserName()).append(':').append(pw.getPassword());
       
   137         String s = encoder.encodeToString(sb.toString().getBytes(ISO_8859_1));
       
   138         String value = "Basic " + s;
       
   139         r.setSystemHeader(hdrname, value);
       
   140     }
       
   141 
       
   142     // Information attached to a HttpRequestImpl relating to authentication
       
   143     static class AuthInfo {
       
   144         final boolean fromcache;
       
   145         final String scheme;
       
   146         int retries;
       
   147         PasswordAuthentication credentials; // used in request
       
   148         CacheEntry cacheEntry; // if used
       
   149 
       
   150         AuthInfo(boolean fromcache,
       
   151                  String scheme,
       
   152                  PasswordAuthentication credentials) {
       
   153             this.fromcache = fromcache;
       
   154             this.scheme = scheme;
       
   155             this.credentials = credentials;
       
   156             this.retries = 1;
       
   157         }
       
   158 
       
   159         AuthInfo(boolean fromcache,
       
   160                  String scheme,
       
   161                  PasswordAuthentication credentials,
       
   162                  CacheEntry ca) {
       
   163             this(fromcache, scheme, credentials);
       
   164             assert credentials == null || (ca != null && ca.value == null);
       
   165             cacheEntry = ca;
       
   166         }
       
   167     }
       
   168 
       
   169     @Override
       
   170     public HttpRequestImpl response(HttpResponseImpl r) throws IOException {
       
   171         Cache cache = getCache(r.request);
       
   172         int status = r.statusCode();
       
   173         HttpHeaders hdrs = r.headers();
       
   174         HttpRequestImpl req = r.request();
       
   175 
       
   176         if (status != UNAUTHORIZED && status != PROXY_UNAUTHORIZED) {
       
   177             // check if any authentication succeeded for first time
       
   178             if (req.exchange.serverauth != null && !req.exchange.serverauth.fromcache) {
       
   179                 AuthInfo au = req.exchange.serverauth;
       
   180                 cache.store(au.scheme, req.uri(), false, au.credentials);
       
   181             }
       
   182             if (req.exchange.proxyauth != null && !req.exchange.proxyauth.fromcache) {
       
   183                 AuthInfo au = req.exchange.proxyauth;
       
   184                 cache.store(au.scheme, req.uri(), false, au.credentials);
       
   185             }
       
   186             return null;
       
   187         }
       
   188 
       
   189         boolean proxy = status == PROXY_UNAUTHORIZED;
       
   190         String authname = proxy ? "Proxy-Authentication" : "WWW-Authenticate";
       
   191         String authval = hdrs.firstValue(authname).orElseThrow(() -> {
       
   192             return new IOException("Invalid auth header");
       
   193         });
       
   194         HeaderParser parser = new HeaderParser(authval);
       
   195         String scheme = parser.findKey(0);
       
   196 
       
   197         // TODO: Need to generalise from Basic only. Delegate to a provider class etc.
       
   198 
       
   199         if (!scheme.equalsIgnoreCase("Basic")) {
       
   200             return null;   // error gets returned to app
       
   201         }
       
   202 
       
   203         String realm = parser.findValue("realm");
       
   204         AuthInfo au = proxy ? req.exchange.proxyauth : req.exchange.serverauth;
       
   205         if (au == null) {
       
   206             PasswordAuthentication pw = getCredentials(authval, proxy, req);
       
   207             if (pw == null) {
       
   208                 throw new IOException("No credentials provided");
       
   209             }
       
   210             // No authentication in request. Get credentials from user
       
   211             au = new AuthInfo(false, "Basic", pw);
       
   212             if (proxy)
       
   213                 req.exchange.proxyauth = au;
       
   214             else
       
   215                 req.exchange.serverauth = au;
       
   216             addBasicCredentials(req, proxy, pw);
       
   217             return req;
       
   218         } else if (au.retries > retry_limit) {
       
   219             throw new IOException("too many authentication attempts");
       
   220         } else {
       
   221             // we sent credentials, but they were rejected
       
   222             if (au.fromcache) {
       
   223                 cache.remove(au.cacheEntry);
       
   224             }
       
   225             // try again
       
   226             au.credentials = getCredentials(authval, proxy, req);
       
   227             addBasicCredentials(req, proxy, au.credentials);
       
   228             au.retries++;
       
   229             return req;
       
   230         }
       
   231     }
       
   232 
       
   233     static final HashMap<HttpClientImpl,Cache> caches = new HashMap<>();
       
   234 
       
   235     static synchronized Cache getCache(HttpRequestImpl req) {
       
   236         HttpClientImpl client = req.client();
       
   237         Cache c = caches.get(client);
       
   238         if (c == null) {
       
   239             c = new Cache();
       
   240             caches.put(client, c);
       
   241         }
       
   242         return c;
       
   243     }
       
   244 
       
   245     static class Cache {
       
   246         final LinkedList<CacheEntry> entries = new LinkedList<>();
       
   247 
       
   248         synchronized CacheEntry get(URI uri, boolean proxy) {
       
   249             for (CacheEntry entry : entries) {
       
   250                 if (entry.equalsKey(uri, proxy)) {
       
   251                     return entry;
       
   252                 }
       
   253             }
       
   254             return null;
       
   255         }
       
   256 
       
   257         synchronized void remove(String authscheme, URI domain, boolean proxy) {
       
   258             for (CacheEntry entry : entries) {
       
   259                 if (entry.equalsKey(domain, proxy)) {
       
   260                     entries.remove(entry);
       
   261                 }
       
   262             }
       
   263         }
       
   264 
       
   265         synchronized void remove(CacheEntry entry) {
       
   266             entries.remove(entry);
       
   267         }
       
   268 
       
   269         synchronized void store(String authscheme,
       
   270                                 URI domain,
       
   271                                 boolean proxy,
       
   272                                 PasswordAuthentication value) {
       
   273             remove(authscheme, domain, proxy);
       
   274             entries.add(new CacheEntry(authscheme, domain, proxy, value));
       
   275         }
       
   276     }
       
   277 
       
   278     static class CacheEntry {
       
   279         final String root;
       
   280         final String scheme;
       
   281         final boolean proxy;
       
   282         final PasswordAuthentication value;
       
   283 
       
   284         CacheEntry(String authscheme,
       
   285                    URI uri,
       
   286                    boolean proxy,
       
   287                    PasswordAuthentication value) {
       
   288             this.scheme = authscheme;
       
   289             this.root = uri.resolve(".").toString(); // remove extraneous components
       
   290             this.proxy = proxy;
       
   291             this.value = value;
       
   292         }
       
   293 
       
   294         public PasswordAuthentication value() {
       
   295             return value;
       
   296         }
       
   297 
       
   298         public boolean equalsKey(URI uri, boolean proxy) {
       
   299             if (this.proxy != proxy) {
       
   300                 return false;
       
   301             }
       
   302             String other = uri.toString();
       
   303             return other.startsWith(root);
       
   304         }
       
   305     }
       
   306 }