8169495: Add a method to set an Authenticator on a HttpURLConnection.
Summary: new public method java.net.HttpURLConnection::setAuthenticator allows to specify an authenticator to use with a given connection.
Reviewed-by: chegar
--- a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java Fri Dec 02 13:18:50 2016 +0000
@@ -39,6 +39,7 @@
import java.net.Proxy;
import java.net.ProtocolException;
import java.io.*;
+import java.net.Authenticator;
import javax.net.ssl.*;
import java.security.Permission;
import java.util.Map;
@@ -489,4 +490,9 @@
public void setChunkedStreamingMode (int chunklen) {
delegate.setChunkedStreamingMode(chunklen);
}
+
+ @Override
+ public void setAuthenticator(Authenticator auth) {
+ delegate.setAuthenticator(auth);
+ }
}
--- a/jdk/src/java.base/share/classes/java/net/Authenticator.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/java/net/Authenticator.java Fri Dec 02 13:18:50 2016 +0000
@@ -25,6 +25,8 @@
package java.net;
+import sun.net.www.protocol.http.AuthenticatorKeys;
+
/**
* The class Authenticator represents an object that knows how to obtain
* authentication for a network connection. Usually, it will do this
@@ -70,6 +72,7 @@
private String requestingScheme;
private URL requestingURL;
private RequestorType requestingAuthType;
+ private final String key = AuthenticatorKeys.computeKey(this);
/**
* The type of the entity requesting authentication.
@@ -349,6 +352,75 @@
}
/**
+ * Ask the given {@code authenticator} for a password. If the given
+ * {@code authenticator} is null, the authenticator, if any, that has been
+ * registered with the system using {@link #setDefault(java.net.Authenticator)
+ * setDefault} is used.
+ * <p>
+ * First, if there is a security manager, its {@code checkPermission}
+ * method is called with a
+ * {@code NetPermission("requestPasswordAuthentication")} permission.
+ * This may result in a java.lang.SecurityException.
+ *
+ * @param authenticator the authenticator, or {@code null}.
+ * @param host The hostname of the site requesting authentication.
+ * @param addr The InetAddress of the site requesting authorization,
+ * or null if not known.
+ * @param port the port for the requested connection
+ * @param protocol The protocol that's requesting the connection
+ * ({@link java.net.Authenticator#getRequestingProtocol()})
+ * @param prompt A prompt string for the user
+ * @param scheme The authentication scheme
+ * @param url The requesting URL that caused the authentication
+ * @param reqType The type (server or proxy) of the entity requesting
+ * authentication.
+ *
+ * @return The username/password, or {@code null} if one can't be gotten.
+ *
+ * @throws SecurityException
+ * if a security manager exists and its
+ * {@code checkPermission} method doesn't allow
+ * the password authentication request.
+ *
+ * @see SecurityManager#checkPermission
+ * @see java.net.NetPermission
+ *
+ * @since 9
+ */
+ public static PasswordAuthentication requestPasswordAuthentication(
+ Authenticator authenticator,
+ String host,
+ InetAddress addr,
+ int port,
+ String protocol,
+ String prompt,
+ String scheme,
+ URL url,
+ RequestorType reqType) {
+
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ NetPermission requestPermission
+ = new NetPermission("requestPasswordAuthentication");
+ sm.checkPermission(requestPermission);
+ }
+
+ Authenticator a = authenticator == null ? theAuthenticator : authenticator;
+ if (a == null) {
+ return null;
+ } else {
+ return a.requestPasswordAuthenticationInstance(host,
+ addr,
+ port,
+ protocol,
+ prompt,
+ scheme,
+ url,
+ reqType);
+ }
+ }
+
+ /**
* Ask this authenticator for a password.
*
* @param host The hostname of the site requesting authentication.
@@ -493,4 +565,11 @@
protected RequestorType getRequestorType () {
return requestingAuthType;
}
+
+ static String getKey(Authenticator a) {
+ return a.key;
+ }
+ static {
+ AuthenticatorKeys.setAuthenticatorKeyAccess(Authenticator::getKey);
+ }
}
--- a/jdk/src/java.base/share/classes/java/net/HttpURLConnection.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/java/net/HttpURLConnection.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -103,6 +103,53 @@
protected long fixedContentLengthLong = -1;
/**
+ * Supplies an {@link java.net.Authenticator Authenticator} to be used
+ * when authentication is requested through the HTTP protocol for
+ * this {@code HttpURLConnection}.
+ * If no authenticator is supplied, the
+ * {@linkplain Authenticator#setDefault(java.net.Authenticator) default
+ * authenticator} will be used.
+ *
+ * @implSpec The default behavior of this method is to unconditionally
+ * throw {@link UnsupportedOperationException}. Concrete
+ * implementations of {@code HttpURLConnection}
+ * which support supplying an {@code Authenticator} for a
+ * specific {@code HttpURLConnection} instance should
+ * override this method to implement a different behavior.
+ *
+ * @implNote Depending on authentication schemes, an implementation
+ * may or may not need to use the provided authenticator
+ * to obtain a password. For instance, an implementation that
+ * relies on third-party security libraries may still invoke the
+ * default authenticator if these libraries are configured
+ * to do so.
+ * Likewise, an implementation that supports transparent
+ * NTLM authentication may let the system attempt
+ * to connect using the system user credentials first,
+ * before invoking the provided authenticator.
+ * <br>
+ * However, if an authenticator is specifically provided,
+ * then the underlying connection may only be reused for
+ * {@code HttpURLConnection} instances which share the same
+ * {@code Authenticator} instance, and authentication information,
+ * if cached, may only be reused for an {@code HttpURLConnection}
+ * sharing that same {@code Authenticator}.
+ *
+ * @param auth The {@code Authenticator} that should be used by this
+ * {@code HttpURLConnection}.
+ *
+ * @throws UnsupportedOperationException if setting an Authenticator is
+ * not supported by the underlying implementation.
+ * @throws IllegalStateException if URLConnection is already connected.
+ * @throws NullPointerException if the supplied {@code auth} is {@code null}.
+ * @since 9
+ */
+ public void setAuthenticator(Authenticator auth) {
+ throw new UnsupportedOperationException("Supplying an authenticator"
+ + " is not supported by " + this.getClass());
+ }
+
+ /**
* Returns the key for the {@code n}<sup>th</sup> header field.
* Some implementations may treat the {@code 0}<sup>th</sup>
* header field as special, i.e. as the status line returned by the HTTP
--- a/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java Fri Dec 02 13:18:50 2016 +0000
@@ -28,6 +28,7 @@
import java.io.*;
import java.net.*;
import java.util.Locale;
+import java.util.Objects;
import java.util.Properties;
import sun.net.NetworkClient;
import sun.net.ProgressSource;
@@ -35,6 +36,7 @@
import sun.net.www.HeaderParser;
import sun.net.www.MeteredStream;
import sun.net.www.ParseUtil;
+import sun.net.www.protocol.http.AuthenticatorKeys;
import sun.net.www.protocol.http.HttpURLConnection;
import sun.util.logging.PlatformLogger;
import static sun.net.www.protocol.http.HttpURLConnection.TunnelState.*;
@@ -132,6 +134,8 @@
}
}
+ protected volatile String authenticatorKey;
+
/**
* A NOP method kept for backwards binary compatibility
* @deprecated -- system properties are no longer cached.
@@ -279,10 +283,12 @@
ret = null;
}
}
-
if (ret != null) {
- if ((ret.proxy != null && ret.proxy.equals(p)) ||
- (ret.proxy == null && p == null)) {
+ String ak = httpuc == null ? AuthenticatorKeys.DEFAULT
+ : httpuc.getAuthenticatorKey();
+ boolean compatible = Objects.equals(ret.proxy, p)
+ && Objects.equals(ret.getAuthenticatorKey(), ak);
+ if (compatible) {
synchronized (ret) {
ret.cachedHttpClient = true;
assert ret.inCache;
@@ -306,6 +312,9 @@
}
if (ret == null) {
ret = new HttpClient(url, p, to);
+ if (httpuc != null) {
+ ret.authenticatorKey = httpuc.getAuthenticatorKey();
+ }
} else {
SecurityManager security = System.getSecurityManager();
if (security != null) {
@@ -341,6 +350,12 @@
to, useCache, httpuc);
}
+ public final String getAuthenticatorKey() {
+ String k = authenticatorKey;
+ if (k == null) return AuthenticatorKeys.DEFAULT;
+ return k;
+ }
+
/* return it to the cache as still usable, if:
* 1) It's keeping alive, AND
* 2) It still has some connections left, AND
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthCache.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthCache.java Fri Dec 02 13:18:50 2016 +0000
@@ -38,7 +38,8 @@
/**
* Put an entry in the cache. pkey is a string specified as follows:
*
- * A:[B:]C:D:E[:F] Between 4 and 6 fields separated by ":"
+ * A:[B:]C:D:E[:F][;key=value] Between 4 and 6 fields separated by ":",
+ * and an optional semicolon-separated key=value list postfix,
* where the fields have the following meaning:
* A is "s" or "p" for server or proxy authentication respectively
* B is optional and is the {@link AuthScheme}, e.g. BASIC, DIGEST, NTLM, etc
@@ -47,6 +48,11 @@
* E is the port number
* F is optional and if present is the realm
*
+ * The semi-colon separated key=value list postfix can be used to
+ * provide additional contextual information, thus allowing
+ * to separate AuthCacheValue instances obtained from different
+ * contexts.
+ *
* Generally, two entries are created for each AuthCacheValue,
* one including the realm and one without the realm.
* Also, for some schemes (digest) multiple entries may be created
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.HashMap;
+import java.util.Objects;
import sun.net.www.HeaderParser;
@@ -190,8 +191,18 @@
/** The shortest path from the URL we authenticated against. */
String path;
+ /**
+ * A key identifying the authenticator from which the credentials
+ * were obtained.
+ * {@link AuthenticatorKeys#DEFAULT} identifies the {@linkplain
+ * java.net.Authenticator#setDefault(java.net.Authenticator) default}
+ * authenticator.
+ */
+ String authenticatorKey;
+
/** Use this constructor only for proxy entries */
- public AuthenticationInfo(char type, AuthScheme authScheme, String host, int port, String realm) {
+ public AuthenticationInfo(char type, AuthScheme authScheme, String host,
+ int port, String realm, String authenticatorKey) {
this.type = type;
this.authScheme = authScheme;
this.protocol = "";
@@ -199,6 +210,7 @@
this.port = port;
this.realm = realm;
this.path = null;
+ this.authenticatorKey = Objects.requireNonNull(authenticatorKey);
}
public Object clone() {
@@ -214,7 +226,8 @@
* Constructor used to limit the authorization to the path within
* the URL. Use this constructor for origin server entries.
*/
- public AuthenticationInfo(char type, AuthScheme authScheme, URL url, String realm) {
+ public AuthenticationInfo(char type, AuthScheme authScheme, URL url, String realm,
+ String authenticatorKey) {
this.type = type;
this.authScheme = authScheme;
this.protocol = url.getProtocol().toLowerCase();
@@ -231,7 +244,16 @@
else {
this.path = reducePath (urlPath);
}
+ this.authenticatorKey = Objects.requireNonNull(authenticatorKey);
+ }
+ /**
+ * The {@linkplain java.net.Authenticator#getKey(java.net.Authenticator) key}
+ * of the authenticator that was used to obtain the credentials.
+ * @return The authenticator's key.
+ */
+ public final String getAuthenticatorKey() {
+ return authenticatorKey;
}
/*
@@ -256,13 +278,14 @@
* don't yet know the realm
* (i.e. when we're preemptively setting the auth).
*/
- static AuthenticationInfo getServerAuth(URL url) {
+ static AuthenticationInfo getServerAuth(URL url, String authenticatorKey) {
int port = url.getPort();
if (port == -1) {
port = url.getDefaultPort();
}
String key = SERVER_AUTHENTICATION + ":" + url.getProtocol().toLowerCase()
- + ":" + url.getHost().toLowerCase() + ":" + port;
+ + ":" + url.getHost().toLowerCase() + ":" + port
+ + ";auth=" + authenticatorKey;
return getAuth(key, url);
}
@@ -272,13 +295,17 @@
* In this case we do not use the path because the protection space
* is identified by the host:port:realm only
*/
- static String getServerAuthKey(URL url, String realm, AuthScheme scheme) {
+ static String getServerAuthKey(URL url, String realm, AuthScheme scheme,
+ String authenticatorKey) {
int port = url.getPort();
if (port == -1) {
port = url.getDefaultPort();
}
- String key = SERVER_AUTHENTICATION + ":" + scheme + ":" + url.getProtocol().toLowerCase()
- + ":" + url.getHost().toLowerCase() + ":" + port + ":" + realm;
+ String key = SERVER_AUTHENTICATION + ":" + scheme + ":"
+ + url.getProtocol().toLowerCase()
+ + ":" + url.getHost().toLowerCase()
+ + ":" + port + ":" + realm
+ + ";auth=" + authenticatorKey;
return key;
}
@@ -309,8 +336,10 @@
* for preemptive header-setting. Note, the protocol field is always
* blank for proxies.
*/
- static AuthenticationInfo getProxyAuth(String host, int port) {
- String key = PROXY_AUTHENTICATION + "::" + host.toLowerCase() + ":" + port;
+ static AuthenticationInfo getProxyAuth(String host, int port,
+ String authenticatorKey) {
+ String key = PROXY_AUTHENTICATION + "::" + host.toLowerCase() + ":" + port
+ + ";auth=" + authenticatorKey;
AuthenticationInfo result = (AuthenticationInfo) cache.get(key, null);
return result;
}
@@ -320,9 +349,12 @@
* Used in response to a challenge. Note, the protocol field is always
* blank for proxies.
*/
- static String getProxyAuthKey(String host, int port, String realm, AuthScheme scheme) {
- String key = PROXY_AUTHENTICATION + ":" + scheme + "::" + host.toLowerCase()
- + ":" + port + ":" + realm;
+ static String getProxyAuthKey(String host, int port, String realm,
+ AuthScheme scheme, String authenticatorKey) {
+ String key = PROXY_AUTHENTICATION + ":" + scheme
+ + "::" + host.toLowerCase()
+ + ":" + port + ":" + realm
+ + ";auth=" + authenticatorKey;
return key;
}
@@ -424,27 +456,34 @@
String cacheKey(boolean includeRealm) {
// This must be kept in sync with the getXXXAuth() methods in this
// class.
+ String authenticatorKey = getAuthenticatorKey();
if (includeRealm) {
return type + ":" + authScheme + ":" + protocol + ":"
- + host + ":" + port + ":" + realm;
+ + host + ":" + port + ":" + realm
+ + ";auth=" + authenticatorKey;
} else {
- return type + ":" + protocol + ":" + host + ":" + port;
+ return type + ":" + protocol + ":" + host + ":" + port
+ + ";auth=" + authenticatorKey;
}
}
String s1, s2; /* used for serialization of pw */
- private void readObject(ObjectInputStream s)
+ private synchronized void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject ();
pw = new PasswordAuthentication (s1, s2.toCharArray());
s1 = null; s2= null;
+ if (authenticatorKey == null) {
+ authenticatorKey = AuthenticatorKeys.DEFAULT;
+ }
}
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
+ Objects.requireNonNull(authenticatorKey);
s1 = pw.getUserName();
s2 = new String (pw.getPassword());
s.defaultWriteObject ();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticatorKeys.java Fri Dec 02 13:18:50 2016 +0000
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.net.www.protocol.http;
+
+import java.net.Authenticator;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * A class used to tie a key to an authenticator instance.
+ */
+public final class AuthenticatorKeys {
+ private AuthenticatorKeys() {
+ throw new InternalError("Trying to instantiate static class");
+ }
+
+ public static final String DEFAULT = "default";
+ private static final AtomicLong IDS = new AtomicLong();
+
+ public static String computeKey(Authenticator a) {
+ return System.identityHashCode(a) + "-" + IDS.incrementAndGet()
+ + "@" + a.getClass().getName();
+ }
+
+ /**
+ * Returns a key for the given authenticator.
+ *
+ * @param authenticator The authenticator; {@code null} should be
+ * passed when the {@linkplain
+ * Authenticator#setDefault(java.net.Authenticator) default}
+ * authenticator is meant.
+ * @return A key for the given authenticator, {@link #DEFAULT} for
+ * {@code null}.
+ */
+ public static String getKey(Authenticator authenticator) {
+ if (authenticator == null) {
+ return DEFAULT;
+ }
+ return authenticatorKeyAccess.getKey(authenticator);
+ }
+
+ @FunctionalInterface
+ public interface AuthenticatorKeyAccess {
+ public String getKey(Authenticator a);
+ }
+
+ private static AuthenticatorKeyAccess authenticatorKeyAccess;
+ public static void setAuthenticatorKeyAccess(AuthenticatorKeyAccess access) {
+ if (authenticatorKeyAccess == null && access != null) {
+ authenticatorKeyAccess = access;
+ }
+ }
+
+}
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
+import java.util.Objects;
import sun.net.www.HeaderParser;
/**
@@ -54,9 +55,11 @@
* Create a BasicAuthentication
*/
public BasicAuthentication(boolean isProxy, String host, int port,
- String realm, PasswordAuthentication pw) {
+ String realm, PasswordAuthentication pw,
+ String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
- AuthScheme.BASIC, host, port, realm);
+ AuthScheme.BASIC, host, port, realm,
+ Objects.requireNonNull(authenticatorKey));
String plain = pw.getUserName() + ":";
byte[] nameBytes = null;
try {
@@ -84,9 +87,11 @@
* Create a BasicAuthentication
*/
public BasicAuthentication(boolean isProxy, String host, int port,
- String realm, String auth) {
+ String realm, String auth,
+ String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
- AuthScheme.BASIC, host, port, realm);
+ AuthScheme.BASIC, host, port, realm,
+ Objects.requireNonNull(authenticatorKey));
this.auth = "Basic " + auth;
}
@@ -94,9 +99,11 @@
* Create a BasicAuthentication
*/
public BasicAuthentication(boolean isProxy, URL url, String realm,
- PasswordAuthentication pw) {
+ PasswordAuthentication pw,
+ String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
- AuthScheme.BASIC, url, realm);
+ AuthScheme.BASIC, url, realm,
+ Objects.requireNonNull(authenticatorKey));
String plain = pw.getUserName() + ":";
byte[] nameBytes = null;
try {
@@ -124,9 +131,10 @@
* Create a BasicAuthentication
*/
public BasicAuthentication(boolean isProxy, URL url, String realm,
- String auth) {
+ String auth, String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
- AuthScheme.BASIC, url, realm);
+ AuthScheme.BASIC, url, realm,
+ Objects.requireNonNull(authenticatorKey));
this.auth = "Basic " + auth;
}
@@ -202,4 +210,3 @@
return npath;
}
}
-
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java Fri Dec 02 13:18:50 2016 +0000
@@ -38,6 +38,7 @@
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedAction;
import java.security.AccessController;
+import java.util.Objects;
import static sun.net.www.protocol.http.HttpURLConnection.HTTP_CONNECT;
/**
@@ -193,11 +194,12 @@
*/
public DigestAuthentication(boolean isProxy, URL url, String realm,
String authMethod, PasswordAuthentication pw,
- Parameters params) {
+ Parameters params, String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.DIGEST,
url,
- realm);
+ realm,
+ Objects.requireNonNull(authenticatorKey));
this.authMethod = authMethod;
this.pw = pw;
this.params = params;
@@ -205,12 +207,13 @@
public DigestAuthentication(boolean isProxy, String host, int port, String realm,
String authMethod, PasswordAuthentication pw,
- Parameters params) {
+ Parameters params, String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.DIGEST,
host,
port,
- realm);
+ realm,
+ Objects.requireNonNull(authenticatorKey));
this.authMethod = authMethod;
this.pw = pw;
this.params = params;
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpCallerInfo.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpCallerInfo.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
package sun.net.www.protocol.http;
+import java.net.Authenticator;
import java.net.Authenticator.RequestorType;
import java.net.InetAddress;
import java.net.URL;
@@ -49,6 +50,7 @@
public final int port;
public final InetAddress addr;
public final RequestorType authType;
+ public final Authenticator authenticator;
/**
* Create a schemed object based on an un-schemed one.
@@ -62,12 +64,13 @@
this.addr = old.addr;
this.authType = old.authType;
this.scheme = scheme;
+ this.authenticator = old.authenticator;
}
/**
* Constructor an un-schemed object for site access.
*/
- public HttpCallerInfo(URL url) {
+ public HttpCallerInfo(URL url, Authenticator a) {
this.url= url;
prompt = "";
host = url.getHost();
@@ -90,12 +93,13 @@
protocol = url.getProtocol();
authType = RequestorType.SERVER;
scheme = "";
+ authenticator = a;
}
/**
* Constructor an un-schemed object for proxy access.
*/
- public HttpCallerInfo(URL url, String host, int port) {
+ public HttpCallerInfo(URL url, String host, int port, Authenticator a) {
this.url= url;
this.host = host;
this.port = port;
@@ -104,5 +108,6 @@
protocol = url.getProtocol();
authType = RequestorType.PROXY;
scheme = "";
+ authenticator = a;
}
}
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -78,6 +78,7 @@
import java.util.TimeZone;
import java.net.MalformedURLException;
import java.nio.ByteBuffer;
+import java.util.Objects;
import java.util.Properties;
import static sun.net.www.protocol.http.AuthScheme.BASIC;
import static sun.net.www.protocol.http.AuthScheme.DIGEST;
@@ -304,6 +305,8 @@
protected HttpClient http;
protected Handler handler;
protected Proxy instProxy;
+ protected volatile Authenticator authenticator;
+ protected volatile String authenticatorKey;
private CookieHandler cookieHandler;
private final ResponseCache cacheHandler;
@@ -433,6 +436,7 @@
*/
private static PasswordAuthentication
privilegedRequestPasswordAuthentication(
+ final Authenticator authenticator,
final String host,
final InetAddress addr,
final int port,
@@ -448,7 +452,7 @@
logger.finest("Requesting Authentication: host =" + host + " url = " + url);
}
PasswordAuthentication pass = Authenticator.requestPasswordAuthentication(
- host, addr, port, protocol,
+ authenticator, host, addr, port, protocol,
prompt, scheme, url, authType);
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null"));
@@ -507,6 +511,22 @@
this.authObj = authObj;
}
+ @Override
+ public synchronized void setAuthenticator(Authenticator auth) {
+ if (connecting || connected) {
+ throw new IllegalStateException(
+ "Authenticator must be set before connecting");
+ }
+ authenticator = Objects.requireNonNull(auth);
+ authenticatorKey = AuthenticatorKeys.getKey(authenticator);
+ }
+
+ public String getAuthenticatorKey() {
+ String k = authenticatorKey;
+ if (k == null) return AuthenticatorKeys.getKey(authenticator);
+ return k;
+ }
+
/*
* checks the validity of http message header and throws
* IllegalArgumentException if invalid.
@@ -631,7 +651,8 @@
requests.setIfNotSet("If-Modified-Since", fo.format(date));
}
// check for preemptive authorization
- AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url);
+ AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url,
+ getAuthenticatorKey());
if (sauth != null && sauth.supportsPreemptiveAuthorization() ) {
// Sets "Authorization"
requests.setIfNotSet(sauth.getHeaderName(), sauth.getHeaderValue(url,method));
@@ -800,15 +821,15 @@
* if present
*/
protected void setProxiedClient (URL url,
- String proxyHost, int proxyPort,
- boolean useCache)
+ String proxyHost, int proxyPort,
+ boolean useCache)
throws IOException {
proxiedConnect(url, proxyHost, proxyPort, useCache);
}
protected void proxiedConnect(URL url,
- String proxyHost, int proxyPort,
- boolean useCache)
+ String proxyHost, int proxyPort,
+ boolean useCache)
throws IOException {
http = HttpClient.New (url, proxyHost, proxyPort, useCache,
connectTimeout, this);
@@ -878,10 +899,14 @@
boolean redir;
int redirects = 0;
InputStream in;
+ Authenticator a = null;
do {
if (c instanceof HttpURLConnection) {
((HttpURLConnection) c).setInstanceFollowRedirects(false);
+ if (a == null) {
+ a = ((HttpURLConnection) c).authenticator;
+ }
}
// We want to open the input stream before
@@ -912,6 +937,9 @@
}
redir = true;
c = target.openConnection();
+ if (a != null && c instanceof HttpURLConnection) {
+ ((HttpURLConnection)c).setAuthenticator(a);
+ }
redirects++;
}
}
@@ -1612,7 +1640,8 @@
responses,
new HttpCallerInfo(url,
http.getProxyHostUsed(),
- http.getProxyPortUsed()),
+ http.getProxyPortUsed(),
+ authenticator),
dontUseNegotiate,
disabledProxyingSchemes
);
@@ -1684,7 +1713,7 @@
srvHdr = new AuthenticationHeader (
"WWW-Authenticate", responses,
- new HttpCallerInfo(url),
+ new HttpCallerInfo(url, authenticator),
dontUseNegotiate
);
@@ -1762,7 +1791,8 @@
/* path could be an abs_path or a complete URI */
URL u = new URL (url, path);
DigestAuthentication d = new DigestAuthentication (
- false, u, realm, "Digest", pw, digestparams);
+ false, u, realm, "Digest", pw,
+ digestparams, srv.authenticatorKey);
d.addToCache ();
} catch (Exception e) {}
}
@@ -2065,7 +2095,8 @@
responses,
new HttpCallerInfo(url,
http.getProxyHostUsed(),
- http.getProxyPortUsed()),
+ http.getProxyPortUsed(),
+ authenticator),
dontUseNegotiate,
disabledTunnelingSchemes
);
@@ -2174,7 +2205,8 @@
private void setPreemptiveProxyAuthentication(MessageHeader requests) throws IOException {
AuthenticationInfo pauth
= AuthenticationInfo.getProxyAuth(http.getProxyHostUsed(),
- http.getProxyPortUsed());
+ http.getProxyPortUsed(),
+ getAuthenticatorKey());
if (pauth != null && pauth.supportsPreemptiveAuthorization()) {
String value;
if (pauth instanceof DigestAuthentication) {
@@ -2228,7 +2260,8 @@
if (realm == null)
realm = "";
- proxyAuthKey = AuthenticationInfo.getProxyAuthKey(host, port, realm, authScheme);
+ proxyAuthKey = AuthenticationInfo.getProxyAuthKey(host, port, realm,
+ authScheme, getAuthenticatorKey());
ret = AuthenticationInfo.getProxyAuth(proxyAuthKey);
if (ret == null) {
switch (authScheme) {
@@ -2248,21 +2281,25 @@
}
PasswordAuthentication a =
privilegedRequestPasswordAuthentication(
+ authenticator,
host, addr, port, "http",
realm, scheme, url, RequestorType.PROXY);
if (a != null) {
- ret = new BasicAuthentication(true, host, port, realm, a);
+ ret = new BasicAuthentication(true, host, port, realm, a,
+ getAuthenticatorKey());
}
break;
case DIGEST:
a = privilegedRequestPasswordAuthentication(
+ authenticator,
host, null, port, url.getProtocol(),
realm, scheme, url, RequestorType.PROXY);
if (a != null) {
DigestAuthentication.Parameters params =
new DigestAuthentication.Parameters();
ret = new DigestAuthentication(true, host, port, realm,
- scheme, a, params);
+ scheme, a, params,
+ getAuthenticatorKey());
}
break;
case NTLM:
@@ -2288,6 +2325,7 @@
logger.finest("Trying Transparent NTLM authentication");
} else {
a = privilegedRequestPasswordAuthentication(
+ authenticator,
host, null, port, url.getProtocol(),
"", scheme, url, RequestorType.PROXY);
}
@@ -2299,7 +2337,8 @@
*/
if (tryTransparentNTLMProxy ||
(!tryTransparentNTLMProxy && a != null)) {
- ret = NTLMAuthenticationProxy.proxy.create(true, host, port, a);
+ ret = NTLMAuthenticationProxy.proxy.create(true, host,
+ port, a, getAuthenticatorKey());
}
/* set to false so that we do not try again */
@@ -2330,7 +2369,8 @@
URL u = new URL("http", host, port, "/");
String a = defaultAuth.authString(u, scheme, realm);
if (a != null) {
- ret = new BasicAuthentication (true, host, port, realm, a);
+ ret = new BasicAuthentication (true, host, port, realm, a,
+ getAuthenticatorKey());
// not in cache by default - cache on success
}
} catch (java.net.MalformedURLException ignored) {
@@ -2383,7 +2423,8 @@
domain = p.findValue ("domain");
if (realm == null)
realm = "";
- serverAuthKey = AuthenticationInfo.getServerAuthKey(url, realm, authScheme);
+ serverAuthKey = AuthenticationInfo.getServerAuthKey(url, realm, authScheme,
+ getAuthenticatorKey());
ret = AuthenticationInfo.getServerAuth(serverAuthKey);
InetAddress addr = null;
if (ret == null) {
@@ -2409,19 +2450,24 @@
case BASIC:
PasswordAuthentication a =
privilegedRequestPasswordAuthentication(
+ authenticator,
url.getHost(), addr, port, url.getProtocol(),
realm, scheme, url, RequestorType.SERVER);
if (a != null) {
- ret = new BasicAuthentication(false, url, realm, a);
+ ret = new BasicAuthentication(false, url, realm, a,
+ getAuthenticatorKey());
}
break;
case DIGEST:
a = privilegedRequestPasswordAuthentication(
+ authenticator,
url.getHost(), addr, port, url.getProtocol(),
realm, scheme, url, RequestorType.SERVER);
if (a != null) {
digestparams = new DigestAuthentication.Parameters();
- ret = new DigestAuthentication(false, url, realm, scheme, a, digestparams);
+ ret = new DigestAuthentication(false, url, realm, scheme,
+ a, digestparams,
+ getAuthenticatorKey());
}
break;
case NTLM:
@@ -2452,6 +2498,7 @@
logger.finest("Trying Transparent NTLM authentication");
} else {
a = privilegedRequestPasswordAuthentication(
+ authenticator,
url.getHost(), addr, port, url.getProtocol(),
"", scheme, url, RequestorType.SERVER);
}
@@ -2464,7 +2511,8 @@
*/
if (tryTransparentNTLMServer ||
(!tryTransparentNTLMServer && a != null)) {
- ret = NTLMAuthenticationProxy.proxy.create(false, url1, a);
+ ret = NTLMAuthenticationProxy.proxy.create(false,
+ url1, a, getAuthenticatorKey());
}
/* set to false so that we do not try again */
@@ -2488,7 +2536,8 @@
&& defaultAuth.schemeSupported(scheme)) {
String a = defaultAuth.authString(url, scheme, realm);
if (a != null) {
- ret = new BasicAuthentication (false, url, realm, a);
+ ret = new BasicAuthentication (false, url, realm, a,
+ getAuthenticatorKey());
// not in cache by default - cache on success
}
}
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -45,21 +45,22 @@
static final boolean supported = proxy != null ? true : false;
static final boolean supportsTransparentAuth = supported ? supportsTransparentAuth() : false;
- private final Constructor<? extends AuthenticationInfo> threeArgCtr;
- private final Constructor<? extends AuthenticationInfo> fiveArgCtr;
+ private final Constructor<? extends AuthenticationInfo> fourArgCtr;
+ private final Constructor<? extends AuthenticationInfo> sixArgCtr;
- private NTLMAuthenticationProxy(Constructor<? extends AuthenticationInfo> threeArgCtr,
- Constructor<? extends AuthenticationInfo> fiveArgCtr) {
- this.threeArgCtr = threeArgCtr;
- this.fiveArgCtr = fiveArgCtr;
+ private NTLMAuthenticationProxy(Constructor<? extends AuthenticationInfo> fourArgCtr,
+ Constructor<? extends AuthenticationInfo> sixArgCtr) {
+ this.fourArgCtr = fourArgCtr;
+ this.sixArgCtr = sixArgCtr;
}
AuthenticationInfo create(boolean isProxy,
URL url,
- PasswordAuthentication pw) {
+ PasswordAuthentication pw,
+ String authenticatorKey) {
try {
- return threeArgCtr.newInstance(isProxy, url, pw);
+ return fourArgCtr.newInstance(isProxy, url, pw, authenticatorKey);
} catch (ReflectiveOperationException roe) {
finest(roe);
}
@@ -70,9 +71,10 @@
AuthenticationInfo create(boolean isProxy,
String host,
int port,
- PasswordAuthentication pw) {
+ PasswordAuthentication pw,
+ String authenticatorKey) {
try {
- return fiveArgCtr.newInstance(isProxy, host, port, pw);
+ return sixArgCtr.newInstance(isProxy, host, port, pw, authenticatorKey);
} catch (ReflectiveOperationException roe) {
finest(roe);
}
@@ -115,21 +117,23 @@
@SuppressWarnings("unchecked")
private static NTLMAuthenticationProxy tryLoadNTLMAuthentication() {
Class<? extends AuthenticationInfo> cl;
- Constructor<? extends AuthenticationInfo> threeArg, fiveArg;
+ Constructor<? extends AuthenticationInfo> fourArg, sixArg;
try {
cl = (Class<? extends AuthenticationInfo>)Class.forName(clazzStr, true, null);
if (cl != null) {
- threeArg = cl.getConstructor(boolean.class,
+ fourArg = cl.getConstructor(boolean.class,
URL.class,
- PasswordAuthentication.class);
- fiveArg = cl.getConstructor(boolean.class,
+ PasswordAuthentication.class,
+ String.class);
+ sixArg = cl.getConstructor(boolean.class,
String.class,
int.class,
- PasswordAuthentication.class);
+ PasswordAuthentication.class,
+ String.class);
supportsTA = cl.getDeclaredMethod(supportsTAStr);
isTrustedSite = cl.getDeclaredMethod(isTrustedSiteStr, java.net.URL.class);
- return new NTLMAuthenticationProxy(threeArg,
- fiveArg);
+ return new NTLMAuthenticationProxy(fourArg,
+ sixArg);
}
} catch (ClassNotFoundException cnfe) {
finest(cnfe);
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -68,7 +68,8 @@
super(RequestorType.PROXY==hci.authType ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
hci.scheme.equalsIgnoreCase("Negotiate") ? NEGOTIATE : KERBEROS,
hci.url,
- "");
+ "",
+ AuthenticatorKeys.getKey(hci.authenticator));
this.hci = hci;
}
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -39,6 +39,7 @@
import java.net.Proxy;
import java.security.Principal;
import java.security.cert.*;
+import java.util.Objects;
import java.util.StringTokenizer;
import java.util.Vector;
@@ -46,6 +47,7 @@
import javax.net.ssl.*;
import sun.net.www.http.HttpClient;
+import sun.net.www.protocol.http.AuthenticatorKeys;
import sun.net.www.protocol.http.HttpURLConnection;
import sun.security.action.*;
@@ -334,8 +336,12 @@
}
if (ret != null) {
- if ((ret.proxy != null && ret.proxy.equals(p)) ||
- (ret.proxy == null && p == Proxy.NO_PROXY)) {
+ String ak = httpuc == null ? AuthenticatorKeys.DEFAULT
+ : httpuc.getAuthenticatorKey();
+ boolean compatible = ((ret.proxy != null && ret.proxy.equals(p)) ||
+ (ret.proxy == null && p == Proxy.NO_PROXY))
+ && Objects.equals(ret.getAuthenticatorKey(), ak);
+ if (compatible) {
synchronized (ret) {
ret.cachedHttpClient = true;
assert ret.inCache;
@@ -364,6 +370,9 @@
}
if (ret == null) {
ret = new HttpsClient(sf, url, p, connectTimeout);
+ if (httpuc != null) {
+ ret.authenticatorKey = httpuc.getAuthenticatorKey();
+ }
} else {
SecurityManager security = System.getSecurityManager();
if (security != null) {
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -39,6 +39,7 @@
import java.net.Proxy;
import java.net.ProtocolException;
import java.io.*;
+import java.net.Authenticator;
import javax.net.ssl.*;
import java.security.Permission;
import java.security.Principal;
@@ -517,4 +518,9 @@
public void setChunkedStreamingMode (int chunklen) {
delegate.setChunkedStreamingMode(chunklen);
}
+
+ @Override
+ public void setAuthenticator(Authenticator auth) {
+ delegate.setAuthenticator(auth);
+ }
}
--- a/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,7 @@
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Base64;
+import java.util.Objects;
import sun.net.www.HeaderParser;
import sun.net.www.protocol.http.AuthenticationInfo;
@@ -116,11 +117,13 @@
* If this notation is not used, then the domain will be taken
* from a system property: "http.auth.ntlm.domain".
*/
- public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) {
+ public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw,
+ String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.NTLM,
url,
- "");
+ "",
+ Objects.requireNonNull(authenticatorKey));
init (pw);
}
@@ -157,12 +160,14 @@
* Constructor used for proxy entries
*/
public NTLMAuthentication(boolean isProxy, String host, int port,
- PasswordAuthentication pw) {
+ PasswordAuthentication pw,
+ String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.NTLM,
host,
port,
- "");
+ "",
+ Objects.requireNonNull(authenticatorKey));
init (pw);
}
@@ -242,4 +247,3 @@
return result;
}
}
-
--- a/jdk/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
import java.net.PasswordAuthentication;
import java.net.UnknownHostException;
import java.net.URL;
+import java.util.Objects;
import sun.net.www.HeaderParser;
import sun.net.www.protocol.http.AuthenticationInfo;
import sun.net.www.protocol.http.AuthScheme;
@@ -88,11 +89,13 @@
* If this notation is not used, then the domain will be taken
* from a system property: "http.auth.ntlm.domain".
*/
- public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) {
+ public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw,
+ String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.NTLM,
url,
- "");
+ "",
+ Objects.requireNonNull(authenticatorKey));
init (pw);
}
@@ -122,12 +125,14 @@
* Constructor used for proxy entries
*/
public NTLMAuthentication(boolean isProxy, String host, int port,
- PasswordAuthentication pw) {
+ PasswordAuthentication pw,
+ String authenticatorKey) {
super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION,
AuthScheme.NTLM,
host,
port,
- "");
+ "",
+ Objects.requireNonNull(authenticatorKey));
init (pw);
}
--- a/jdk/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java Fri Dec 02 13:18:50 2016 +0000
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,7 @@
answered = true;
PasswordAuthentication passAuth =
Authenticator.requestPasswordAuthentication(
+ hci.authenticator,
hci.host, hci.addr, hci.port, hci.protocol,
hci.prompt, hci.scheme, hci.url, hci.authType);
/**
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPSetAuthenticatorTest.java Fri Dec 02 13:18:50 2016 +0000
@@ -0,0 +1,295 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.IOException;
+import java.net.Authenticator;
+import java.net.HttpURLConnection;
+import java.net.Proxy;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * @test
+ * @bug 8169415
+ * @library /lib/testlibrary/
+ * @modules java.base/sun.net.www
+ * java.base/sun.net.www.protocol.http
+ * jdk.httpserver/sun.net.httpserver
+ * @build jdk.testlibrary.SimpleSSLContext HTTPTest HTTPTestServer HTTPTestClient HTTPSetAuthenticatorTest
+ * @summary A simple HTTP test that starts an echo server supporting the given
+ * authentication scheme, then starts a regular HTTP client to invoke it.
+ * The client first does a GET request on "/", then follows on
+ * with a POST request that sends "Hello World!" to the server.
+ * The client expects to receive "Hello World!" in return.
+ * The test supports several execution modes:
+ * SERVER: The server performs Server authentication;
+ * PROXY: The server pretends to be a proxy and performs
+ * Proxy authentication;
+ * SERVER307: The server redirects the client (307) to another
+ * server that perform Server authentication;
+ * PROXY305: The server attempts to redirect
+ * the client to a proxy using 305 code;
+ * This test runs the client several times, providing different
+ * authenticators to the HttpURLConnection and verifies that
+ * the authenticator is invoked as expected - validating that
+ * connections with different authenticators do not share each
+ * other's socket channel and authentication info.
+ * Note: BASICSERVER means that the server will let the underlying
+ * com.sun.net.httpserver.HttpServer perform BASIC
+ * authentication when in Server mode. There should be
+ * no real difference between BASICSERVER and BASIC - it should
+ * be transparent on the client side.
+ * @run main/othervm HTTPSetAuthenticatorTest NONE SERVER PROXY SERVER307 PROXY305
+ * @run main/othervm HTTPSetAuthenticatorTest DIGEST SERVER
+ * @run main/othervm HTTPSetAuthenticatorTest DIGEST PROXY
+ * @run main/othervm HTTPSetAuthenticatorTest DIGEST PROXY305
+ * @run main/othervm HTTPSetAuthenticatorTest DIGEST SERVER307
+ * @run main/othervm HTTPSetAuthenticatorTest BASIC SERVER
+ * @run main/othervm HTTPSetAuthenticatorTest BASIC PROXY
+ * @run main/othervm HTTPSetAuthenticatorTest BASIC PROXY305
+ * @run main/othervm HTTPSetAuthenticatorTest BASIC SERVER307
+ * @run main/othervm HTTPSetAuthenticatorTest BASICSERVER SERVER
+ * @run main/othervm HTTPSetAuthenticatorTest BASICSERVER SERVER307
+ *
+ * @author danielfuchs
+ */
+public class HTTPSetAuthenticatorTest extends HTTPTest {
+
+ public static void main(String[] args) throws Exception {
+ String[] schemes;
+ String[] params;
+ if (args == null || args.length == 0) {
+ schemes = Stream.of(HttpSchemeType.values())
+ .map(HttpSchemeType::name)
+ .collect(Collectors.toList())
+ .toArray(new String[0]);
+ params = new String[0];
+ } else {
+ schemes = new String[] { args[0] };
+ params = Arrays.copyOfRange(args, 1, args.length);
+ }
+ for (String scheme : schemes) {
+ System.out.println("==== Testing with scheme=" + scheme + " ====\n");
+ new HTTPSetAuthenticatorTest(HttpSchemeType.valueOf(scheme))
+ .execute(params);
+ System.out.println();
+ }
+ }
+
+ final HttpSchemeType scheme;
+ public HTTPSetAuthenticatorTest(HttpSchemeType scheme) {
+ this.scheme = scheme;
+ }
+
+ @Override
+ public HttpSchemeType getHttpSchemeType() {
+ return scheme;
+ }
+
+ @Override
+ public int run(HTTPTestServer server,
+ HttpProtocolType protocol,
+ HttpAuthType mode)
+ throws IOException
+ {
+ HttpTestAuthenticator authOne = new HttpTestAuthenticator("dublin", "foox");
+ HttpTestAuthenticator authTwo = new HttpTestAuthenticator("dublin", "foox");
+ int expectedIncrement = scheme == HttpSchemeType.NONE
+ ? 0 : EXPECTED_AUTH_CALLS_PER_TEST;
+ int count;
+ int defaultCount = AUTHENTICATOR.count.get();
+
+ // Connect to the server with a GET request, then with a
+ // POST that contains "Hello World!"
+ // Uses authenticator #1
+ System.out.println("\nClient: Using authenticator #1: "
+ + toString(authOne));
+ HTTPTestClient.connect(protocol, server, mode, authOne);
+ count = authOne.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #1 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+
+ // Connect to the server with a GET request, then with a
+ // POST that contains "Hello World!"
+ // Uses authenticator #2
+ System.out.println("\nClient: Using authenticator #2: "
+ + toString(authTwo));
+ HTTPTestClient.connect(protocol, server, mode, authTwo);
+ count = authTwo.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #2 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+ count = authTwo.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #2 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+
+ // Connect to the server with a GET request, then with a
+ // POST that contains "Hello World!"
+ // Uses authenticator #1
+ System.out.println("\nClient: Using authenticator #1 again: "
+ + toString(authOne));
+ HTTPTestClient.connect(protocol, server, mode, authOne);
+ count = authOne.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #1 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+ count = authTwo.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #2 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+ count = AUTHENTICATOR.count.get();
+ if (count != defaultCount) {
+ throw new AssertionError("Default Authenticator called " + count(count)
+ + " expected it to be called " + expected(defaultCount));
+ }
+
+ // Now tries with the default authenticator: it should be invoked.
+ System.out.println("\nClient: Using the default authenticator: "
+ + toString(null));
+ HTTPTestClient.connect(protocol, server, mode, null);
+ count = authOne.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #1 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+ count = authTwo.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #2 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+ count = AUTHENTICATOR.count.get();
+ if (count != defaultCount + expectedIncrement) {
+ throw new AssertionError("Default Authenticator called " + count(count)
+ + " expected it to be called " + expected(defaultCount + expectedIncrement));
+ }
+
+ // Now tries with explicitly setting the default authenticator: it should
+ // be invoked again.
+ // Uncomment the code below when 8169068 is available.
+// System.out.println("\nClient: Explicitly setting the default authenticator: "
+// + toString(Authenticator.getDefault()));
+// HTTPTestClient.connect(protocol, server, mode, Authenticator.getDefault());
+// count = authOne.count.get();
+// if (count != expectedIncrement) {
+// throw new AssertionError("Authenticator #1 called " + count(count)
+// + " expected it to be called " + expected(expectedIncrement));
+// }
+// count = authTwo.count.get();
+// if (count != expectedIncrement) {
+// throw new AssertionError("Authenticator #2 called " + count(count)
+// + " expected it to be called " + expected(expectedIncrement));
+// }
+// count = AUTHENTICATOR.count.get();
+// if (count != defaultCount + 2 * expectedIncrement) {
+// throw new AssertionError("Default Authenticator called " + count(count)
+// + " expected it to be called "
+// + expected(defaultCount + 2 * expectedIncrement));
+// }
+
+ // Now tries to set an authenticator on a connected connection.
+ URL url = url(protocol, server.getAddress(), "/");
+ Proxy proxy = proxy(server, mode);
+ HttpURLConnection conn = openConnection(url, mode, proxy);
+ try {
+ conn.setAuthenticator(null);
+ throw new RuntimeException("Expected NullPointerException"
+ + " trying to set a null authenticator"
+ + " not raised.");
+ } catch (NullPointerException npe) {
+ System.out.println("Client: caught expected NPE"
+ + " trying to set a null authenticator: "
+ + npe);
+ }
+ conn.connect();
+ try {
+ try {
+ conn.setAuthenticator(authOne);
+ throw new RuntimeException("Expected IllegalStateException"
+ + " trying to set an authenticator after connect"
+ + " not raised.");
+ } catch (IllegalStateException ise) {
+ System.out.println("Client: caught expected ISE"
+ + " trying to set an authenticator after connect: "
+ + ise);
+ }
+ // Uncomment the code below when 8169068 is available.
+// try {
+// conn.setAuthenticator(Authenticator.getDefault());
+// throw new RuntimeException("Expected IllegalStateException"
+// + " trying to set an authenticator after connect"
+// + " not raised.");
+// } catch (IllegalStateException ise) {
+// System.out.println("Client: caught expected ISE"
+// + " trying to set an authenticator after connect: "
+// + ise);
+// }
+ try {
+ conn.setAuthenticator(null);
+ throw new RuntimeException("Expected"
+ + " IllegalStateException or NullPointerException"
+ + " trying to set a null authenticator after connect"
+ + " not raised.");
+ } catch (IllegalStateException | NullPointerException xxe) {
+ System.out.println("Client: caught expected "
+ + xxe.getClass().getSimpleName()
+ + " trying to set a null authenticator after connect: "
+ + xxe);
+ }
+ } finally {
+ conn.disconnect();
+ }
+
+ // double check that authOne and authTwo haven't been invoked.
+ count = authOne.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #1 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+ count = authTwo.count.get();
+ if (count != expectedIncrement) {
+ throw new AssertionError("Authenticator #2 called " + count(count)
+ + " expected it to be called " + expected(expectedIncrement));
+ }
+
+ // All good!
+ // return the number of times the default authenticator is supposed
+ // to have been called.
+ return scheme == HttpSchemeType.NONE ? 0 : 1 * EXPECTED_AUTH_CALLS_PER_TEST;
+ }
+
+ static String toString(Authenticator a) {
+ return sun.net.www.protocol.http.AuthenticatorKeys.getKey(a);
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java Fri Dec 02 13:18:50 2016 +0000
@@ -0,0 +1,283 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.Authenticator;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.PasswordAuthentication;
+import java.net.Proxy;
+import java.net.URL;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.stream.Stream;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import jdk.testlibrary.SimpleSSLContext;
+
+/**
+ * @test
+ * @bug 8169415
+ * @library /lib/testlibrary/
+ * @modules java.base/sun.net.www
+ * jdk.httpserver/sun.net.httpserver
+ * @build jdk.testlibrary.SimpleSSLContext HTTPTest HTTPTestServer HTTPTestClient
+ * @summary A simple HTTP test that starts an echo server supporting Digest
+ * authentication, then starts a regular HTTP client to invoke it.
+ * The client first does a GET request on "/", then follows on
+ * with a POST request that sends "Hello World!" to the server.
+ * The client expects to receive "Hello World!" in return.
+ * The test supports several execution modes:
+ * SERVER: The server performs Digest Server authentication;
+ * PROXY: The server pretends to be a proxy and performs
+ * Digest Proxy authentication;
+ * SERVER307: The server redirects the client (307) to another
+ * server that perform Digest authentication;
+ * PROXY305: The server attempts to redirect
+ * the client to a proxy using 305 code;
+ * @run main/othervm HTTPTest SERVER
+ * @run main/othervm HTTPTest PROXY
+ * @run main/othervm HTTPTest SERVER307
+ * @run main/othervm HTTPTest PROXY305
+ *
+ * @author danielfuchs
+ */
+public class HTTPTest {
+
+ public static final boolean DEBUG =
+ Boolean.parseBoolean(System.getProperty("test.debug", "false"));
+ public static enum HttpAuthType { SERVER, PROXY, SERVER307, PROXY305 };
+ public static enum HttpProtocolType { HTTP, HTTPS };
+ public static enum HttpSchemeType { NONE, BASICSERVER, BASIC, DIGEST };
+ public static final HttpAuthType DEFAULT_HTTP_AUTH_TYPE = HttpAuthType.SERVER;
+ public static final HttpProtocolType DEFAULT_PROTOCOL_TYPE = HttpProtocolType.HTTP;
+ public static final HttpSchemeType DEFAULT_SCHEME_TYPE = HttpSchemeType.DIGEST;
+
+ public static class HttpTestAuthenticator extends Authenticator {
+ private final String realm;
+ private final String username;
+ // Used to prevent incrementation of 'count' when calling the
+ // authenticator from the server side.
+ private final ThreadLocal<Boolean> skipCount = new ThreadLocal<>();
+ // count will be incremented every time getPasswordAuthentication()
+ // is called from the client side.
+ final AtomicInteger count = new AtomicInteger();
+
+ public HttpTestAuthenticator(String realm, String username) {
+ this.realm = realm;
+ this.username = username;
+ }
+
+ @Override
+ protected PasswordAuthentication getPasswordAuthentication() {
+ if (skipCount.get() == null || skipCount.get().booleanValue() == false) {
+ System.out.println("Authenticator called: " + count.incrementAndGet());
+ }
+ return new PasswordAuthentication(getUserName(),
+ new char[] {'b','a','r'});
+ }
+
+ // Called by the server side to get the password of the user
+ // being authentified.
+ public final char[] getPassword(String user) {
+ if (user.equals(username)) {
+ skipCount.set(Boolean.TRUE);
+ try {
+ return getPasswordAuthentication().getPassword();
+ } finally {
+ skipCount.set(Boolean.FALSE);
+ }
+ }
+ throw new SecurityException("User unknown: " + user);
+ }
+
+ public final String getUserName() {
+ return username;
+ }
+ public final String getRealm() {
+ return realm;
+ }
+
+ }
+ public static final HttpTestAuthenticator AUTHENTICATOR;
+ static {
+ AUTHENTICATOR = new HttpTestAuthenticator("dublin", "foox");
+ Authenticator.setDefault(AUTHENTICATOR);
+ }
+
+ static {
+ try {
+ HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
+ });
+ SSLContext.setDefault(new SimpleSSLContext().get());
+ } catch (IOException ex) {
+ throw new ExceptionInInitializerError(ex);
+ }
+ }
+
+ static final Logger logger = Logger.getLogger ("com.sun.net.httpserver");
+ static {
+ if (DEBUG) logger.setLevel(Level.ALL);
+ Stream.of(Logger.getLogger("").getHandlers())
+ .forEach(h -> h.setLevel(Level.ALL));
+ }
+
+ static final int EXPECTED_AUTH_CALLS_PER_TEST = 1;
+
+ public static void main(String[] args) throws Exception {
+ // new HTTPTest().execute(HttpAuthType.SERVER.name());
+ new HTTPTest().execute(args);
+ }
+
+ public void execute(String... args) throws Exception {
+ Stream<HttpAuthType> modes;
+ if (args == null || args.length == 0) {
+ modes = Stream.of(HttpAuthType.values());
+ } else {
+ modes = Stream.of(args).map(HttpAuthType::valueOf);
+ }
+ modes.forEach(this::test);
+ System.out.println("Test PASSED - Authenticator called: "
+ + expected(AUTHENTICATOR.count.get()));
+ }
+
+ public void test(HttpAuthType mode) {
+ for (HttpProtocolType type: HttpProtocolType.values()) {
+ test(type, mode);
+ }
+ }
+
+ public HttpSchemeType getHttpSchemeType() {
+ return DEFAULT_SCHEME_TYPE;
+ }
+
+ public void test(HttpProtocolType protocol, HttpAuthType mode) {
+ if (mode == HttpAuthType.PROXY305 && protocol == HttpProtocolType.HTTPS ) {
+ // silently skip unsupported test combination
+ return;
+ }
+ System.out.println("\n**** Testing " + protocol + " "
+ + mode + " mode ****\n");
+ int authCount = AUTHENTICATOR.count.get();
+ int expectedIncrement = 0;
+ try {
+ // Creates an HTTP server that echoes back whatever is in the
+ // request body.
+ HTTPTestServer server =
+ HTTPTestServer.create(protocol,
+ mode,
+ AUTHENTICATOR,
+ getHttpSchemeType());
+ try {
+ expectedIncrement += run(server, protocol, mode);
+ } finally {
+ server.stop();
+ }
+ } catch (IOException ex) {
+ ex.printStackTrace(System.err);
+ throw new UncheckedIOException(ex);
+ }
+ int count = AUTHENTICATOR.count.get();
+ if (count != authCount + expectedIncrement) {
+ throw new AssertionError("Authenticator called " + count(count)
+ + " expected it to be called "
+ + expected(authCount + expectedIncrement));
+ }
+ }
+
+ /**
+ * Runs the test with the given parameters.
+ * @param server The server
+ * @param protocol The protocol (HTTP/HTTPS)
+ * @param mode The mode (PROXY, SERVER, SERVER307...)
+ * @return The number of times the default authenticator should have been
+ * called.
+ * @throws IOException in case of connection or protocol issues
+ */
+ public int run(HTTPTestServer server,
+ HttpProtocolType protocol,
+ HttpAuthType mode)
+ throws IOException
+ {
+ // Connect to the server with a GET request, then with a
+ // POST that contains "Hello World!"
+ HTTPTestClient.connect(protocol, server, mode, null);
+ // return the number of times the default authenticator is supposed
+ // to have been called.
+ return EXPECTED_AUTH_CALLS_PER_TEST;
+ }
+
+ public static String count(int count) {
+ switch(count) {
+ case 0: return "not even once";
+ case 1: return "once";
+ case 2: return "twice";
+ default: return String.valueOf(count) + " times";
+ }
+ }
+
+ public static String expected(int count) {
+ switch(count) {
+ default: return count(count);
+ }
+ }
+ public static String protocol(HttpProtocolType type) {
+ return type.name().toLowerCase(Locale.US);
+ }
+
+ public static URL url(HttpProtocolType protocol, InetSocketAddress address,
+ String path) throws MalformedURLException {
+ return new URL(protocol(protocol),
+ address.getHostString(),
+ address.getPort(), path);
+ }
+
+ public static Proxy proxy(HTTPTestServer server, HttpAuthType authType) {
+ return (authType == HttpAuthType.PROXY)
+ ? new Proxy(Proxy.Type.HTTP, server.getAddress())
+ : null;
+ }
+
+ public static HttpURLConnection openConnection(URL url,
+ HttpAuthType authType,
+ Proxy proxy)
+ throws IOException {
+
+ HttpURLConnection conn = (HttpURLConnection)
+ (authType == HttpAuthType.PROXY
+ ? url.openConnection(proxy)
+ : url.openConnection());
+ return conn;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTestClient.java Fri Dec 02 13:18:50 2016 +0000
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.IOException;
+import java.net.Authenticator;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.URL;
+import javax.net.ssl.HttpsURLConnection;
+
+/**
+ * A simple Http client that connects to the HTTPTestServer.
+ * @author danielfuchs
+ */
+public class HTTPTestClient extends HTTPTest {
+
+ public static void connect(HttpProtocolType protocol,
+ HTTPTestServer server,
+ HttpAuthType authType,
+ Authenticator auth)
+ throws IOException {
+
+ InetSocketAddress address = server.getAddress();
+ final URL url = url(protocol, address, "/");
+ final Proxy proxy = proxy(server, authType);
+
+ System.out.println("Client: FIRST request: " + url + " GET");
+ HttpURLConnection conn = openConnection(url, authType, proxy);
+ configure(conn, auth);
+ System.out.println("Response code: " + conn.getResponseCode());
+ String result = new String(conn.getInputStream().readAllBytes(), "UTF-8");
+ System.out.println("Response body: " + result);
+ if (!result.isEmpty()) {
+ throw new RuntimeException("Unexpected response to GET: " + result);
+ }
+ System.out.println("\nClient: NEXT request: " + url + " POST");
+ conn = openConnection(url, authType, proxy);
+ configure(conn, auth);
+ conn.setRequestMethod("POST");
+ conn.setDoOutput(true);
+ conn.setDoInput(true);
+ conn.getOutputStream().write("Hello World!".getBytes("UTF-8"));
+ System.out.println("Response code: " + conn.getResponseCode());
+ result = new String(conn.getInputStream().readAllBytes(), "UTF-8");
+ System.out.println("Response body: " + result);
+ if ("Hello World!".equals(result)) {
+ System.out.println("Test passed!");
+ } else {
+ throw new RuntimeException("Unexpected response to POST: " + result);
+ }
+ }
+
+ private static void configure(HttpURLConnection conn, Authenticator auth)
+ throws IOException {
+ if (auth != null) {
+ conn.setAuthenticator(auth);
+ }
+ if (conn instanceof HttpsURLConnection) {
+ System.out.println("Client: configuring SSL connection");
+ // We have set a default SSLContext so we don't need to do
+ // anything here. Otherwise it could look like:
+ // HttpsURLConnection httpsConn = (HttpsURLConnection)conn;
+ // httpsConn.setSSLSocketFactory(
+ // new SimpleSSLContext().get().getSocketFactory());
+ }
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java Fri Dec 02 13:18:50 2016 +0000
@@ -0,0 +1,995 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.sun.net.httpserver.BasicAuthenticator;
+import com.sun.net.httpserver.Filter;
+import com.sun.net.httpserver.Headers;
+import com.sun.net.httpserver.HttpContext;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
+import com.sun.net.httpserver.HttpsConfigurator;
+import com.sun.net.httpserver.HttpsParameters;
+import com.sun.net.httpserver.HttpsServer;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.Writer;
+import java.math.BigInteger;
+import java.net.HttpURLConnection;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.URL;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.List;
+import java.util.Objects;
+import java.util.Random;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import sun.net.www.HeaderParser;
+
+/**
+ * A simple HTTP server that supports Digest authentication.
+ * By default this server will echo back whatever is present
+ * in the request body.
+ * @author danielfuchs
+ */
+public class HTTPTestServer extends HTTPTest {
+
+ final HttpServer serverImpl; // this server endpoint
+ final HTTPTestServer redirect; // the target server where to redirect 3xx
+ final HttpHandler delegate; // unused
+
+ private HTTPTestServer(HttpServer server, HTTPTestServer target,
+ HttpHandler delegate) {
+ this.serverImpl = server;
+ this.redirect = target;
+ this.delegate = delegate;
+ }
+
+ public static void main(String[] args)
+ throws IOException {
+
+ HTTPTestServer server = create(HTTPTest.DEFAULT_PROTOCOL_TYPE,
+ HTTPTest.DEFAULT_HTTP_AUTH_TYPE,
+ HTTPTest.AUTHENTICATOR,
+ HTTPTest.DEFAULT_SCHEME_TYPE);
+ try {
+ System.out.println("Server created at " + server.getAddress());
+ System.out.println("Strike <Return> to exit");
+ System.in.read();
+ } finally {
+ System.out.println("stopping server");
+ server.stop();
+ }
+ }
+
+ private static String toString(Headers headers) {
+ return headers.entrySet().stream()
+ .map((e) -> e.getKey() + ": " + e.getValue())
+ .collect(Collectors.joining("\n"));
+ }
+
+ public static HTTPTestServer create(HttpProtocolType protocol,
+ HttpAuthType authType,
+ HttpTestAuthenticator auth,
+ HttpSchemeType schemeType)
+ throws IOException {
+ return create(protocol, authType, auth, schemeType, null);
+ }
+
+ public static HTTPTestServer create(HttpProtocolType protocol,
+ HttpAuthType authType,
+ HttpTestAuthenticator auth,
+ HttpSchemeType schemeType,
+ HttpHandler delegate)
+ throws IOException {
+ Objects.requireNonNull(authType);
+ Objects.requireNonNull(auth);
+ switch(authType) {
+ // A server that performs Server Digest authentication.
+ case SERVER: return createServer(protocol, authType, auth,
+ schemeType, delegate, "/");
+ // A server that pretends to be a Proxy and performs
+ // Proxy Digest authentication. If protocol is HTTPS,
+ // then this will create a HttpsProxyTunnel that will
+ // handle the CONNECT request for tunneling.
+ case PROXY: return createProxy(protocol, authType, auth,
+ schemeType, delegate, "/");
+ // A server that sends 307 redirect to a server that performs
+ // Digest authentication.
+ // Note: 301 doesn't work here because it transforms POST into GET.
+ case SERVER307: return createServerAndRedirect(protocol,
+ HttpAuthType.SERVER,
+ auth, schemeType,
+ delegate, 307);
+ // A server that sends 305 redirect to a proxy that performs
+ // Digest authentication.
+ case PROXY305: return createServerAndRedirect(protocol,
+ HttpAuthType.PROXY,
+ auth, schemeType,
+ delegate, 305);
+ default:
+ throw new InternalError("Unknown server type: " + authType);
+ }
+ }
+
+ static HttpServer createHttpServer(HttpProtocolType protocol) throws IOException {
+ switch (protocol) {
+ case HTTP: return HttpServer.create();
+ case HTTPS: return configure(HttpsServer.create());
+ default: throw new InternalError("Unsupported protocol " + protocol);
+ }
+ }
+
+ static HttpsServer configure(HttpsServer server) throws IOException {
+ try {
+ SSLContext ctx = SSLContext.getDefault();
+ server.setHttpsConfigurator(new Configurator(ctx));
+ } catch (NoSuchAlgorithmException ex) {
+ throw new IOException(ex);
+ }
+ return server;
+ }
+
+
+ static void setContextAuthenticator(HttpContext ctxt,
+ HttpTestAuthenticator auth) {
+ final String realm = auth.getRealm();
+ com.sun.net.httpserver.Authenticator authenticator =
+ new BasicAuthenticator(realm) {
+ @Override
+ public boolean checkCredentials(String username, String pwd) {
+ return auth.getUserName().equals(username)
+ && new String(auth.getPassword(username)).equals(pwd);
+ }
+ };
+ ctxt.setAuthenticator(authenticator);
+ }
+
+ public static HTTPTestServer createServer(HttpProtocolType protocol,
+ HttpAuthType authType,
+ HttpTestAuthenticator auth,
+ HttpSchemeType schemeType,
+ HttpHandler delegate,
+ String path)
+ throws IOException {
+ Objects.requireNonNull(authType);
+ Objects.requireNonNull(auth);
+
+ HttpServer impl = createHttpServer(protocol);
+ final HTTPTestServer server = new HTTPTestServer(impl, null, delegate);
+ final HttpHandler hh = server.createHandler(schemeType, auth, authType);
+ HttpContext ctxt = impl.createContext(path, hh);
+ server.configureAuthentication(ctxt, schemeType, auth, authType);
+ impl.bind(new InetSocketAddress("127.0.0.1", 0), 0);
+ impl.start();
+ return server;
+ }
+
+ public static HTTPTestServer createProxy(HttpProtocolType protocol,
+ HttpAuthType authType,
+ HttpTestAuthenticator auth,
+ HttpSchemeType schemeType,
+ HttpHandler delegate,
+ String path)
+ throws IOException {
+ Objects.requireNonNull(authType);
+ Objects.requireNonNull(auth);
+
+ HttpServer impl = createHttpServer(protocol);
+ final HTTPTestServer server = protocol == HttpProtocolType.HTTPS
+ ? new HttpsProxyTunnel(impl, null, delegate)
+ : new HTTPTestServer(impl, null, delegate);
+ final HttpHandler hh = server.createHandler(schemeType, auth, authType);
+ HttpContext ctxt = impl.createContext(path, hh);
+ server.configureAuthentication(ctxt, schemeType, auth, authType);
+
+ impl.bind(new InetSocketAddress("127.0.0.1", 0), 0);
+ impl.start();
+
+ return server;
+ }
+
+ public static HTTPTestServer createServerAndRedirect(
+ HttpProtocolType protocol,
+ HttpAuthType targetAuthType,
+ HttpTestAuthenticator auth,
+ HttpSchemeType schemeType,
+ HttpHandler targetDelegate,
+ int code300)
+ throws IOException {
+ Objects.requireNonNull(targetAuthType);
+ Objects.requireNonNull(auth);
+
+ // The connection between client and proxy can only
+ // be a plain connection: SSL connection to proxy
+ // is not supported by our client connection.
+ HttpProtocolType targetProtocol = targetAuthType == HttpAuthType.PROXY
+ ? HttpProtocolType.HTTP
+ : protocol;
+ HTTPTestServer redirectTarget =
+ (targetAuthType == HttpAuthType.PROXY)
+ ? createProxy(protocol, targetAuthType,
+ auth, schemeType, targetDelegate, "/")
+ : createServer(targetProtocol, targetAuthType,
+ auth, schemeType, targetDelegate, "/");
+ HttpServer impl = createHttpServer(protocol);
+ final HTTPTestServer redirectingServer =
+ new HTTPTestServer(impl, redirectTarget, null);
+ InetSocketAddress redirectAddr = redirectTarget.getAddress();
+ URL locationURL = url(targetProtocol, redirectAddr, "/");
+ final HttpHandler hh = redirectingServer.create300Handler(locationURL,
+ HttpAuthType.SERVER, code300);
+ impl.createContext("/", hh);
+ impl.bind(new InetSocketAddress("127.0.0.1", 0), 0);
+ impl.start();
+ return redirectingServer;
+ }
+
+ public InetSocketAddress getAddress() {
+ return serverImpl.getAddress();
+ }
+
+ public void stop() {
+ serverImpl.stop(0);
+ if (redirect != null) {
+ redirect.stop();
+ }
+ }
+
+ protected void writeResponse(HttpExchange he) throws IOException {
+ if (delegate == null) {
+ he.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
+ he.getResponseBody().write(he.getRequestBody().readAllBytes());
+ } else {
+ delegate.handle(he);
+ }
+ }
+
+ private HttpHandler createHandler(HttpSchemeType schemeType,
+ HttpTestAuthenticator auth,
+ HttpAuthType authType) {
+ return new HttpNoAuthHandler(authType);
+ }
+
+ private void configureAuthentication(HttpContext ctxt,
+ HttpSchemeType schemeType,
+ HttpTestAuthenticator auth,
+ HttpAuthType authType) {
+ switch(schemeType) {
+ case DIGEST:
+ // DIGEST authentication is handled by the handler.
+ ctxt.getFilters().add(new HttpDigestFilter(auth, authType));
+ break;
+ case BASIC:
+ // BASIC authentication is handled by the filter.
+ ctxt.getFilters().add(new HttpBasicFilter(auth, authType));
+ break;
+ case BASICSERVER:
+ switch(authType) {
+ case PROXY: case PROXY305:
+ // HttpServer can't support Proxy-type authentication
+ // => we do as if BASIC had been specified, and we will
+ // handle authentication in the handler.
+ ctxt.getFilters().add(new HttpBasicFilter(auth, authType));
+ break;
+ case SERVER: case SERVER307:
+ // Basic authentication is handled by HttpServer
+ // directly => the filter should not perform
+ // authentication again.
+ setContextAuthenticator(ctxt, auth);
+ ctxt.getFilters().add(new HttpNoAuthFilter(authType));
+ break;
+ default:
+ throw new InternalError("Invalid combination scheme="
+ + schemeType + " authType=" + authType);
+ }
+ case NONE:
+ // No authentication at all.
+ ctxt.getFilters().add(new HttpNoAuthFilter(authType));
+ break;
+ default:
+ throw new InternalError("No such scheme: " + schemeType);
+ }
+ }
+
+ private HttpHandler create300Handler(URL proxyURL,
+ HttpAuthType type, int code300) throws MalformedURLException {
+ return new Http3xxHandler(proxyURL, type, code300);
+ }
+
+ // Abstract HTTP filter class.
+ private abstract static class AbstractHttpFilter extends Filter {
+
+ final HttpAuthType authType;
+ final String type;
+ public AbstractHttpFilter(HttpAuthType authType, String type) {
+ this.authType = authType;
+ this.type = type;
+ }
+
+ String getLocation() {
+ return "Location";
+ }
+ String getAuthenticate() {
+ return authType == HttpAuthType.PROXY
+ ? "Proxy-Authenticate" : "WWW-Authenticate";
+ }
+ String getAuthorization() {
+ return authType == HttpAuthType.PROXY
+ ? "Proxy-Authorization" : "Authorization";
+ }
+ int getUnauthorizedCode() {
+ return authType == HttpAuthType.PROXY
+ ? HttpURLConnection.HTTP_PROXY_AUTH
+ : HttpURLConnection.HTTP_UNAUTHORIZED;
+ }
+ String getKeepAlive() {
+ return "keep-alive";
+ }
+ String getConnection() {
+ return authType == HttpAuthType.PROXY
+ ? "Proxy-Connection" : "Connection";
+ }
+ protected abstract boolean isAuthentified(HttpExchange he) throws IOException;
+ protected abstract void requestAuthentication(HttpExchange he) throws IOException;
+ protected void accept(HttpExchange he, Chain chain) throws IOException {
+ chain.doFilter(he);
+ }
+
+ @Override
+ public String description() {
+ return "Filter for " + type;
+ }
+ @Override
+ public void doFilter(HttpExchange he, Chain chain) throws IOException {
+ try {
+ System.out.println(type + ": Got " + he.getRequestMethod()
+ + ": " + he.getRequestURI()
+ + "\n" + HTTPTestServer.toString(he.getRequestHeaders()));
+ if (!isAuthentified(he)) {
+ try {
+ requestAuthentication(he);
+ he.sendResponseHeaders(getUnauthorizedCode(), 0);
+ System.out.println(type
+ + ": Sent back " + getUnauthorizedCode());
+ } finally {
+ he.close();
+ }
+ } else {
+ accept(he, chain);
+ }
+ } catch (RuntimeException | Error | IOException t) {
+ System.err.println(type
+ + ": Unexpected exception while handling request: " + t);
+ t.printStackTrace(System.err);
+ he.close();
+ throw t;
+ }
+ }
+
+ }
+
+ private final static class DigestResponse {
+ final String realm;
+ final String username;
+ final String nonce;
+ final String cnonce;
+ final String nc;
+ final String uri;
+ final String algorithm;
+ final String response;
+ final String qop;
+ final String opaque;
+
+ public DigestResponse(String realm, String username, String nonce,
+ String cnonce, String nc, String uri,
+ String algorithm, String qop, String opaque,
+ String response) {
+ this.realm = realm;
+ this.username = username;
+ this.nonce = nonce;
+ this.cnonce = cnonce;
+ this.nc = nc;
+ this.uri = uri;
+ this.algorithm = algorithm;
+ this.qop = qop;
+ this.opaque = opaque;
+ this.response = response;
+ }
+
+ String getAlgorithm(String defval) {
+ return algorithm == null ? defval : algorithm;
+ }
+ String getQoP(String defval) {
+ return qop == null ? defval : qop;
+ }
+
+ // Code stolen from DigestAuthentication:
+
+ private static final char charArray[] = {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
+ };
+
+ private static String encode(String src, char[] passwd, MessageDigest md) {
+ try {
+ md.update(src.getBytes("ISO-8859-1"));
+ } catch (java.io.UnsupportedEncodingException uee) {
+ assert false;
+ }
+ if (passwd != null) {
+ byte[] passwdBytes = new byte[passwd.length];
+ for (int i=0; i<passwd.length; i++)
+ passwdBytes[i] = (byte)passwd[i];
+ md.update(passwdBytes);
+ Arrays.fill(passwdBytes, (byte)0x00);
+ }
+ byte[] digest = md.digest();
+
+ StringBuilder res = new StringBuilder(digest.length * 2);
+ for (int i = 0; i < digest.length; i++) {
+ int hashchar = ((digest[i] >>> 4) & 0xf);
+ res.append(charArray[hashchar]);
+ hashchar = (digest[i] & 0xf);
+ res.append(charArray[hashchar]);
+ }
+ return res.toString();
+ }
+
+ public static String computeDigest(boolean isRequest,
+ String reqMethod,
+ char[] password,
+ DigestResponse params)
+ throws NoSuchAlgorithmException
+ {
+
+ String A1, HashA1;
+ String algorithm = params.getAlgorithm("MD5");
+ boolean md5sess = algorithm.equalsIgnoreCase ("MD5-sess");
+
+ MessageDigest md = MessageDigest.getInstance(md5sess?"MD5":algorithm);
+
+ if (params.username == null) {
+ throw new IllegalArgumentException("missing username");
+ }
+ if (params.realm == null) {
+ throw new IllegalArgumentException("missing realm");
+ }
+ if (params.uri == null) {
+ throw new IllegalArgumentException("missing uri");
+ }
+ if (params.nonce == null) {
+ throw new IllegalArgumentException("missing nonce");
+ }
+
+ A1 = params.username + ":" + params.realm + ":";
+ HashA1 = encode(A1, password, md);
+
+ String A2;
+ if (isRequest) {
+ A2 = reqMethod + ":" + params.uri;
+ } else {
+ A2 = ":" + params.uri;
+ }
+ String HashA2 = encode(A2, null, md);
+ String combo, finalHash;
+
+ if ("auth".equals(params.qop)) { /* RRC2617 when qop=auth */
+ if (params.cnonce == null) {
+ throw new IllegalArgumentException("missing nonce");
+ }
+ if (params.nc == null) {
+ throw new IllegalArgumentException("missing nonce");
+ }
+ combo = HashA1+ ":" + params.nonce + ":" + params.nc + ":" +
+ params.cnonce + ":auth:" +HashA2;
+
+ } else { /* for compatibility with RFC2069 */
+ combo = HashA1 + ":" +
+ params.nonce + ":" +
+ HashA2;
+ }
+ finalHash = encode(combo, null, md);
+ return finalHash;
+ }
+
+ public static DigestResponse create(String raw) {
+ String username, realm, nonce, nc, uri, response, cnonce,
+ algorithm, qop, opaque;
+ HeaderParser parser = new HeaderParser(raw);
+ username = parser.findValue("username");
+ realm = parser.findValue("realm");
+ nonce = parser.findValue("nonce");
+ nc = parser.findValue("nc");
+ uri = parser.findValue("uri");
+ cnonce = parser.findValue("cnonce");
+ response = parser.findValue("response");
+ algorithm = parser.findValue("algorithm");
+ qop = parser.findValue("qop");
+ opaque = parser.findValue("opaque");
+ return new DigestResponse(realm, username, nonce, cnonce, nc, uri,
+ algorithm, qop, opaque, response);
+ }
+
+ }
+
+ private class HttpNoAuthFilter extends AbstractHttpFilter {
+
+ public HttpNoAuthFilter(HttpAuthType authType) {
+ super(authType, authType == HttpAuthType.SERVER
+ ? "NoAuth Server" : "NoAuth Proxy");
+ }
+
+ @Override
+ protected boolean isAuthentified(HttpExchange he) throws IOException {
+ return true;
+ }
+
+ @Override
+ protected void requestAuthentication(HttpExchange he) throws IOException {
+ throw new InternalError("Should not com here");
+ }
+
+ @Override
+ public String description() {
+ return "Passthrough Filter";
+ }
+
+ }
+
+ // An HTTP Filter that performs Basic authentication
+ private class HttpBasicFilter extends AbstractHttpFilter {
+
+ private final HttpTestAuthenticator auth;
+ public HttpBasicFilter(HttpTestAuthenticator auth, HttpAuthType authType) {
+ super(authType, authType == HttpAuthType.SERVER
+ ? "Basic Server" : "Basic Proxy");
+ this.auth = auth;
+ }
+
+ @Override
+ protected void requestAuthentication(HttpExchange he)
+ throws IOException {
+ he.getResponseHeaders().add(getAuthenticate(),
+ "Basic realm=\"" + auth.getRealm() + "\"");
+ System.out.println(type + ": Requesting Basic Authentication "
+ + he.getResponseHeaders().getFirst(getAuthenticate()));
+ }
+
+ @Override
+ protected boolean isAuthentified(HttpExchange he) {
+ if (he.getRequestHeaders().containsKey(getAuthorization())) {
+ List<String> authorization =
+ he.getRequestHeaders().get(getAuthorization());
+ for (String a : authorization) {
+ System.out.println(type + ": processing " + a);
+ int sp = a.indexOf(' ');
+ if (sp < 0) return false;
+ String scheme = a.substring(0, sp);
+ if (!"Basic".equalsIgnoreCase(scheme)) {
+ System.out.println(type + ": Unsupported scheme '"
+ + scheme +"'");
+ return false;
+ }
+ if (a.length() <= sp+1) {
+ System.out.println(type + ": value too short for '"
+ + scheme +"'");
+ return false;
+ }
+ a = a.substring(sp+1);
+ return validate(a);
+ }
+ return false;
+ }
+ return false;
+ }
+
+ boolean validate(String a) {
+ byte[] b = Base64.getDecoder().decode(a);
+ String userpass = new String (b);
+ int colon = userpass.indexOf (':');
+ String uname = userpass.substring (0, colon);
+ String pass = userpass.substring (colon+1);
+ return auth.getUserName().equals(uname) &&
+ new String(auth.getPassword(uname)).equals(pass);
+ }
+
+ @Override
+ public String description() {
+ return "Filter for " + type;
+ }
+
+ }
+
+
+ // An HTTP Filter that performs Digest authentication
+ private class HttpDigestFilter extends AbstractHttpFilter {
+
+ // This is a very basic DIGEST - used only for the purpose of testing
+ // the client implementation. Therefore we can get away with never
+ // updating the server nonce as it makes the implementation of the
+ // server side digest simpler.
+ private final HttpTestAuthenticator auth;
+ private final byte[] nonce;
+ private final String ns;
+ public HttpDigestFilter(HttpTestAuthenticator auth, HttpAuthType authType) {
+ super(authType, authType == HttpAuthType.SERVER
+ ? "Digest Server" : "Digest Proxy");
+ this.auth = auth;
+ nonce = new byte[16];
+ new Random(Instant.now().toEpochMilli()).nextBytes(nonce);
+ ns = new BigInteger(1, nonce).toString(16);
+ }
+
+ @Override
+ protected void requestAuthentication(HttpExchange he)
+ throws IOException {
+ he.getResponseHeaders().add(getAuthenticate(),
+ "Digest realm=\"" + auth.getRealm() + "\","
+ + "\r\n qop=\"auth\","
+ + "\r\n nonce=\"" + ns +"\"");
+ System.out.println(type + ": Requesting Digest Authentication "
+ + he.getResponseHeaders().getFirst(getAuthenticate()));
+ }
+
+ @Override
+ protected boolean isAuthentified(HttpExchange he) {
+ if (he.getRequestHeaders().containsKey(getAuthorization())) {
+ List<String> authorization = he.getRequestHeaders().get(getAuthorization());
+ for (String a : authorization) {
+ System.out.println(type + ": processing " + a);
+ int sp = a.indexOf(' ');
+ if (sp < 0) return false;
+ String scheme = a.substring(0, sp);
+ if (!"Digest".equalsIgnoreCase(scheme)) {
+ System.out.println(type + ": Unsupported scheme '" + scheme +"'");
+ return false;
+ }
+ if (a.length() <= sp+1) {
+ System.out.println(type + ": value too short for '" + scheme +"'");
+ return false;
+ }
+ a = a.substring(sp+1);
+ DigestResponse dgr = DigestResponse.create(a);
+ return validate(he.getRequestMethod(), dgr);
+ }
+ return false;
+ }
+ return false;
+ }
+
+ boolean validate(String reqMethod, DigestResponse dg) {
+ if (!"MD5".equalsIgnoreCase(dg.getAlgorithm("MD5"))) {
+ System.out.println(type + ": Unsupported algorithm "
+ + dg.algorithm);
+ return false;
+ }
+ if (!"auth".equalsIgnoreCase(dg.getQoP("auth"))) {
+ System.out.println(type + ": Unsupported qop "
+ + dg.qop);
+ return false;
+ }
+ try {
+ if (!dg.nonce.equals(ns)) {
+ System.out.println(type + ": bad nonce returned by client: "
+ + nonce + " expected " + ns);
+ return false;
+ }
+ if (dg.response == null) {
+ System.out.println(type + ": missing digest response.");
+ return false;
+ }
+ char[] pa = auth.getPassword(dg.username);
+ return verify(reqMethod, dg, pa);
+ } catch(IllegalArgumentException | SecurityException
+ | NoSuchAlgorithmException e) {
+ System.out.println(type + ": " + e.getMessage());
+ return false;
+ }
+ }
+
+ boolean verify(String reqMethod, DigestResponse dg, char[] pw)
+ throws NoSuchAlgorithmException {
+ String response = DigestResponse.computeDigest(true, reqMethod, pw, dg);
+ if (!dg.response.equals(response)) {
+ System.out.println(type + ": bad response returned by client: "
+ + dg.response + " expected " + response);
+ return false;
+ } else {
+ System.out.println(type + ": verified response " + response);
+ }
+ return true;
+ }
+
+ @Override
+ public String description() {
+ return "Filter for DIGEST authentication";
+ }
+ }
+
+ // Abstract HTTP handler class.
+ private abstract static class AbstractHttpHandler implements HttpHandler {
+
+ final HttpAuthType authType;
+ final String type;
+ public AbstractHttpHandler(HttpAuthType authType, String type) {
+ this.authType = authType;
+ this.type = type;
+ }
+
+ String getLocation() {
+ return "Location";
+ }
+
+ @Override
+ public void handle(HttpExchange he) throws IOException {
+ try {
+ sendResponse(he);
+ } catch (RuntimeException | Error | IOException t) {
+ System.err.println(type
+ + ": Unexpected exception while handling request: " + t);
+ t.printStackTrace(System.err);
+ throw t;
+ } finally {
+ he.close();
+ }
+ }
+
+ protected abstract void sendResponse(HttpExchange he) throws IOException;
+
+ }
+
+ private class HttpNoAuthHandler extends AbstractHttpHandler {
+
+ public HttpNoAuthHandler(HttpAuthType authType) {
+ super(authType, authType == HttpAuthType.SERVER
+ ? "NoAuth Server" : "NoAuth Proxy");
+ }
+
+ @Override
+ protected void sendResponse(HttpExchange he) throws IOException {
+ HTTPTestServer.this.writeResponse(he);
+ }
+
+ }
+
+ // A dummy HTTP Handler that redirects all incoming requests
+ // by sending a back 3xx response code (301, 305, 307 etc..)
+ private class Http3xxHandler extends AbstractHttpHandler {
+
+ private final URL redirectTargetURL;
+ private final int code3XX;
+ public Http3xxHandler(URL proxyURL, HttpAuthType authType, int code300) {
+ super(authType, "Server" + code300);
+ this.redirectTargetURL = proxyURL;
+ this.code3XX = code300;
+ }
+
+ int get3XX() {
+ return code3XX;
+ }
+
+ @Override
+ public void sendResponse(HttpExchange he) throws IOException {
+ System.out.println(type + ": Got " + he.getRequestMethod()
+ + ": " + he.getRequestURI()
+ + "\n" + HTTPTestServer.toString(he.getRequestHeaders()));
+ System.out.println(type + ": Redirecting to "
+ + (authType == HttpAuthType.PROXY305
+ ? "proxy" : "server"));
+ he.getResponseHeaders().add(getLocation(),
+ redirectTargetURL.toExternalForm().toString());
+ he.sendResponseHeaders(get3XX(), 0);
+ System.out.println(type + ": Sent back " + get3XX() + " "
+ + getLocation() + ": " + redirectTargetURL.toExternalForm().toString());
+ }
+ }
+
+ static class Configurator extends HttpsConfigurator {
+ public Configurator(SSLContext ctx) {
+ super(ctx);
+ }
+
+ @Override
+ public void configure (HttpsParameters params) {
+ params.setSSLParameters (getSSLContext().getSupportedSSLParameters());
+ }
+ }
+
+ // This is a bit hacky: HttpsProxyTunnel is an HTTPTestServer hidden
+ // behind a fake proxy that only understands CONNECT requests.
+ // The fake proxy is just a server socket that intercept the
+ // CONNECT and then redirect streams to the real server.
+ static class HttpsProxyTunnel extends HTTPTestServer
+ implements Runnable {
+
+ final ServerSocket ss;
+ public HttpsProxyTunnel(HttpServer server, HTTPTestServer target,
+ HttpHandler delegate)
+ throws IOException {
+ super(server, target, delegate);
+ System.out.flush();
+ System.err.println("WARNING: HttpsProxyTunnel is an experimental test class");
+ ss = new ServerSocket(0, 0, InetAddress.getByName("127.0.0.1"));
+ start();
+ }
+
+ final void start() throws IOException {
+ Thread t = new Thread(this, "ProxyThread");
+ t.setDaemon(true);
+ t.start();
+ }
+
+ @Override
+ public void stop() {
+ super.stop();
+ try {
+ ss.close();
+ } catch (IOException ex) {
+ if (DEBUG) ex.printStackTrace(System.out);
+ }
+ }
+
+ // Pipe the input stream to the output stream.
+ private synchronized Thread pipe(InputStream is, OutputStream os, char tag) {
+ return new Thread("TunnelPipe("+tag+")") {
+ @Override
+ public void run() {
+ try {
+ try {
+ int c;
+ while ((c = is.read()) != -1) {
+ os.write(c);
+ os.flush();
+ // if DEBUG prints a + or a - for each transferred
+ // character.
+ if (DEBUG) System.out.print(tag);
+ }
+ is.close();
+ } finally {
+ os.close();
+ }
+ } catch (IOException ex) {
+ if (DEBUG) ex.printStackTrace(System.out);
+ }
+ }
+ };
+ }
+
+ @Override
+ public InetSocketAddress getAddress() {
+ return new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort());
+ }
+
+ // This is a bit shaky. It doesn't handle continuation
+ // lines, but our client shouldn't send any.
+ // Read a line from the input stream, swallowing the final
+ // \r\n sequence. Stops at the first \n, doesn't complain
+ // if it wasn't preceded by '\r'.
+ //
+ String readLine(InputStream r) throws IOException {
+ StringBuilder b = new StringBuilder();
+ int c;
+ while ((c = r.read()) != -1) {
+ if (c == '\n') break;
+ b.appendCodePoint(c);
+ }
+ if (b.codePointAt(b.length() -1) == '\r') {
+ b.delete(b.length() -1, b.length());
+ }
+ return b.toString();
+ }
+
+ @Override
+ public void run() {
+ Socket clientConnection = null;
+ try {
+ while (true) {
+ System.out.println("Tunnel: Waiting for client");
+ Socket previous = clientConnection;
+ try {
+ clientConnection = ss.accept();
+ } catch (IOException io) {
+ if (DEBUG) io.printStackTrace(System.out);
+ break;
+ } finally {
+ // close the previous connection
+ if (previous != null) previous.close();
+ }
+ System.out.println("Tunnel: Client accepted");
+ Socket targetConnection = null;
+ InputStream ccis = clientConnection.getInputStream();
+ OutputStream ccos = clientConnection.getOutputStream();
+ Writer w = new OutputStreamWriter(
+ clientConnection.getOutputStream(), "UTF-8");
+ PrintWriter pw = new PrintWriter(w);
+ System.out.println("Tunnel: Reading request line");
+ String requestLine = readLine(ccis);
+ System.out.println("Tunnel: Request line: " + requestLine);
+ if (requestLine.startsWith("CONNECT ")) {
+ // We should probably check that the next word following
+ // CONNECT is the host:port of our HTTPS serverImpl.
+ // Some improvement for a followup!
+
+ // Read all headers until we find the empty line that
+ // signals the end of all headers.
+ while(!requestLine.equals("")) {
+ System.out.println("Tunnel: Reading header: "
+ + (requestLine = readLine(ccis)));
+ }
+
+ targetConnection = new Socket(
+ serverImpl.getAddress().getAddress(),
+ serverImpl.getAddress().getPort());
+
+ // Then send the 200 OK response to the client
+ System.out.println("Tunnel: Sending "
+ + "HTTP/1.1 200 OK\r\n\r\n");
+ pw.print("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
+ pw.flush();
+ } else {
+ // This should not happen. If it does let our serverImpl
+ // deal with it.
+ throw new IOException("Tunnel: Unexpected status line: "
+ + requestLine);
+ }
+
+ // Pipe the input stream of the client connection to the
+ // output stream of the target connection and conversely.
+ // Now the client and target will just talk to each other.
+ System.out.println("Tunnel: Starting tunnel pipes");
+ Thread t1 = pipe(ccis, targetConnection.getOutputStream(), '+');
+ Thread t2 = pipe(targetConnection.getInputStream(), ccos, '-');
+ t1.start();
+ t2.start();
+
+ // We have only 1 client... wait until it has finished before
+ // accepting a new connection request.
+ t1.join();
+ t2.join();
+ }
+ } catch (Throwable ex) {
+ try {
+ ss.close();
+ } catch (IOException ex1) {
+ ex.addSuppressed(ex1);
+ }
+ ex.printStackTrace(System.err);
+ }
+ }
+
+ }
+}
--- a/jdk/test/java/net/HttpURLConnection/getResponseCode.java Fri Dec 02 02:01:40 2016 -0800
+++ b/jdk/test/java/net/HttpURLConnection/getResponseCode.java Fri Dec 02 13:18:50 2016 +0000
@@ -24,6 +24,8 @@
/*
* @test
* @bug 4666195
+ * @build getResponseCode
+ * @run main getResponseCode
* @summary REGRESSION: HttpURLConnection.getResponseCode() returns always -1
*/
import java.net.*;