Path: blob/master/test/jdk/java/net/Authenticator/B4678055.java
41149 views
/*1* Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 467805526* @library /test/lib27* @run main/othervm B467805528* @run main/othervm -Djava.net.preferIPv6Addresses=true B467805529* @summary Basic Authentication fails with multiple realms30*/3132import java.io.IOException;33import java.io.InputStream;34import java.io.PrintWriter;35import java.net.Authenticator;36import java.net.InetAddress;37import java.net.InetSocketAddress;38import java.net.PasswordAuthentication;39import java.net.ProxySelector;40import java.net.URL;41import java.net.URLConnection;42import java.util.concurrent.Executors;4344import com.sun.net.httpserver.HttpExchange;45import com.sun.net.httpserver.HttpHandler;46import com.sun.net.httpserver.HttpServer;47import jdk.test.lib.net.URIBuilder;4849public class B4678055 implements HttpHandler {5051static volatile int count = 0;52static volatile String authstring;5354private void errorReply(HttpExchange req, String reply) throws IOException {55req.getResponseHeaders().set("Connection", "close");56req.getResponseHeaders().set("WWW-Authenticate", reply);57req.sendResponseHeaders(401, -1);58}5960private void okReply (HttpExchange req) throws IOException {61req.sendResponseHeaders(200, 0);62try(PrintWriter pw = new PrintWriter(req.getResponseBody())) {63pw.print("Hello .");64}65}6667public void handle (HttpExchange req) {68try {69System.out.println("Server handling case: "+ count);70if(req.getRequestHeaders().get("Authorization") != null) {71authstring = req.getRequestHeaders().get("Authorization").get(0);72System.out.println(authstring);73}74switch (count) {75case 0:76errorReply (req, "Basic realm=\"wallyworld\"");77break;78case 1:79/* client stores a username/pw for wallyworld80*/81okReply (req);82break;83case 2:84/* emulates a server that has configured a second85* realm, but by misconfiguration uses the same86* realm string as the previous one.87*88* An alternative (more likely) scenario that shows this behavior is89* the case where the password in the original realm has changed90*/91errorReply (req, "Basic realm=\"wallyworld\"");92break;93case 3:94/* The client replies with the username/password95* from the first realm, which is wrong (unexpectedly)96*/97errorReply (req, "Basic realm=\"wallyworld\"");98break;99case 4:100/* The client re-prompts for a password and101* we now reply with an OK. The client with the bug102* will throw NPE at this point.103*/104case 5:105/* Repeat the OK, to make sure the same new auth string is sent */106okReply (req);107break;108}109count ++;110} catch (IOException e) {111System.err.println("Unexpected exception for case " + count + ": " + e);112e.printStackTrace();113}114}115116static void read (InputStream is) throws IOException {117int c;118System.out.println ("reading");119while ((c=is.read()) != -1) {120System.out.write (c);121}122System.out.println ("");123System.out.println ("finished reading");124}125126static boolean checkFinalAuth () {127return authstring.equals ("Basic dXNlcjpwYXNzMg==");128}129130static void client (String u) throws Exception {131URL url = new URL (u);132System.out.println ("client opening connection to: " + u);133URLConnection urlc = url.openConnection ();134InputStream is = urlc.getInputStream ();135read (is);136is.close();137}138139static HttpServer server;140141public static void main (String[] args) throws Exception {142B4678055 b4678055 = new B4678055();143MyAuthenticator auth = new MyAuthenticator ();144Authenticator.setDefault (auth);145ProxySelector.setDefault(ProxySelector.of(null)); // no proxy146try {147InetAddress loopback = InetAddress.getLoopbackAddress();148server = HttpServer.create(new InetSocketAddress(loopback, 0), 10);149server.createContext("/", b4678055);150server.setExecutor(Executors.newSingleThreadExecutor());151server.start();152String serverURL = URIBuilder.newBuilder()153.scheme("http")154.loopback()155.port(server.getAddress().getPort())156.path("/")157.build()158.toString();159System.out.println("Server: listening at: " + serverURL);160client(serverURL + "d1/foo.html");161client(serverURL + "d2/foo.html");162client(serverURL + "d2/foo.html");163} catch (Exception e) {164System.out.println("Client got exception: " + e);165System.out.println("Terminating server");166if (server != null) {167server.stop(1);168}169throw e;170}171int f = auth.getCount();172if (f != 2) {173except ("Authenticator was called "+f+" times. Should be 2");174}175/* this checks the authorization string corresponding to second password "pass2"*/176if (!checkFinalAuth()) {177except ("Wrong authorization string received from client");178}179System.out.println("Terminating server");180server.stop(1);181}182183public static void except (String s) {184System.out.println("Check failed: " + s);185System.out.println("Terminating server");186server.stop(1);187throw new RuntimeException (s);188}189190static class MyAuthenticator extends Authenticator {191MyAuthenticator () {192super ();193}194195volatile int count = 0;196197public PasswordAuthentication getPasswordAuthentication () {198PasswordAuthentication pw;199if (count == 0) {200pw = new PasswordAuthentication ("user", "pass1".toCharArray());201} else {202pw = new PasswordAuthentication ("user", "pass2".toCharArray());203}204count ++;205return pw;206}207208public int getCount () {209return (count);210}211}212}213214215