Path: blob/master/test/jdk/java/net/httpclient/BasicAuthTest.java
41149 views
/*1* Copyright (c) 2015, 2018, 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 808711226* @modules java.net.http27* jdk.httpserver28* @run main/othervm BasicAuthTest29* @summary Basic Authentication Test30*/3132import com.sun.net.httpserver.BasicAuthenticator;33import com.sun.net.httpserver.HttpContext;34import com.sun.net.httpserver.HttpExchange;35import com.sun.net.httpserver.HttpHandler;36import com.sun.net.httpserver.HttpServer;37import java.io.IOException;38import java.io.InputStream;39import java.io.OutputStream;40import java.net.InetAddress;41import java.net.InetSocketAddress;42import java.net.PasswordAuthentication;43import java.net.URI;44import java.net.http.HttpClient;45import java.net.http.HttpRequest;46import java.net.http.HttpRequest.BodyPublishers;47import java.net.http.HttpResponse;48import java.net.http.HttpResponse.BodyHandlers;49import java.util.concurrent.ExecutorService;50import java.util.concurrent.Executors;51import static java.nio.charset.StandardCharsets.US_ASCII;5253public class BasicAuthTest {5455static volatile boolean ok;56static final String RESPONSE = "Hello world";57static final String POST_BODY = "This is the POST body 123909090909090";5859public static void main(String[] args) throws Exception {60InetSocketAddress addr = new InetSocketAddress(InetAddress.getLoopbackAddress(),0);61HttpServer server = HttpServer.create(addr, 10);62ExecutorService e = Executors.newCachedThreadPool();63Handler h = new Handler();64HttpContext serverContext = server.createContext("/test", h);65int port = server.getAddress().getPort();66System.out.println("Server port = " + port);6768ClientAuth ca = new ClientAuth();69ServerAuth sa = new ServerAuth("foo realm");70serverContext.setAuthenticator(sa);71server.setExecutor(e);72server.start();73HttpClient client = HttpClient.newBuilder()74.authenticator(ca)75.build();7677try {78URI uri = new URI("http://localhost:" + Integer.toString(port) + "/test/foo");79HttpRequest req = HttpRequest.newBuilder(uri).GET().build();8081HttpResponse resp = client.send(req, BodyHandlers.ofString());82ok = resp.statusCode() == 200 && resp.body().equals(RESPONSE);8384if (!ok || ca.count != 1)85throw new RuntimeException("Test failed");8687// repeat same request, should succeed but no additional authenticator calls8889resp = client.send(req, BodyHandlers.ofString());90ok = resp.statusCode() == 200 && resp.body().equals(RESPONSE);9192if (!ok || ca.count != 1)93throw new RuntimeException("Test failed");9495// try a POST9697req = HttpRequest.newBuilder(uri)98.POST(BodyPublishers.ofString(POST_BODY))99.build();100resp = client.send(req, BodyHandlers.ofString());101ok = resp.statusCode() == 200;102103if (!ok || ca.count != 1)104throw new RuntimeException("Test failed");105} finally {106server.stop(0);107e.shutdownNow();108}109System.out.println("OK");110}111112static class ServerAuth extends BasicAuthenticator {113114ServerAuth(String realm) {115super(realm);116}117118@Override119public boolean checkCredentials(String username, String password) {120if (!"user".equals(username) || !"passwd".equals(password)) {121return false;122}123return true;124}125126}127128static class ClientAuth extends java.net.Authenticator {129volatile int count = 0;130131@Override132protected PasswordAuthentication getPasswordAuthentication() {133count++;134return new PasswordAuthentication("user", "passwd".toCharArray());135}136}137138static class Handler implements HttpHandler {139static volatile boolean ok;140141@Override142public void handle(HttpExchange he) throws IOException {143String method = he.getRequestMethod();144InputStream is = he.getRequestBody();145if (method.equalsIgnoreCase("POST")) {146String requestBody = new String(is.readAllBytes(), US_ASCII);147if (!requestBody.equals(POST_BODY)) {148he.sendResponseHeaders(500, -1);149ok = false;150} else {151he.sendResponseHeaders(200, -1);152ok = true;153}154} else { // GET155he.sendResponseHeaders(200, RESPONSE.length());156OutputStream os = he.getResponseBody();157os.write(RESPONSE.getBytes(US_ASCII));158os.close();159ok = true;160}161}162}163}164165166