Path: blob/master/test/jdk/sun/net/www/protocol/http/B5017051.java
41159 views
/*1* Copyright (c) 2005, 2019, 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 5017051 636077426* @modules jdk.httpserver27* @library /test/lib28* @run main/othervm B501705129* @run main/othervm -Djava.net.preferIPv6Addresses=true B501705130* @summary Tests CR 5017051 & 636077431*/3233import java.net.*;34import java.util.*;35import java.io.*;36import com.sun.net.httpserver.*;37import java.util.concurrent.Executors;38import java.util.concurrent.ExecutorService;39import jdk.test.lib.net.URIBuilder;4041/*42* Part 1:43* First request sent to the http server will not have an "Authorization" header set and44* the server will respond with a 401, but not until it has set a cookie in the response45* headers. The subsequent request ( comes from HttpURLConnection's authentication retry )46* will have the appropriate Authorization header and the servers context handler will be47* invoked. The test passes only if the client (HttpURLConnection) has sent the cookie48* in its second request that had been set via the first response from the server.49*50* Part 2:51* Preload the CookieManager with a cookie. Make a http request that requires authentication52* The cookie will be sent in the first request (without the Authorization header), the53* server will respond with a 401 (from MyBasicAuthFilter) and the client will add the54* appropriate Authorization header. This tests ensures that there is only one Cookie header55* in the request that actually makes it to the Http servers context handler.56*/5758public class B501705159{60HttpServer httpServer;61ExecutorService executorService;6263public static void main(String[] args) throws Exception {64new B5017051();65}6667public B5017051() throws Exception {68startHttpServer();69doClient();70}7172void doClient() throws Exception {73java.net.Authenticator.setDefault(new MyAuthenticator());74CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));75ProxySelector.setDefault(ProxySelector.of(null));7677try {78InetSocketAddress address = httpServer.getAddress();7980// Part 181URL url = URIBuilder.newBuilder()82.scheme("http")83.host(address.getAddress())84.port(address.getPort())85.path("/test/")86.toURL();87HttpURLConnection uc = (HttpURLConnection)url.openConnection();88int resp = uc.getResponseCode();89if (resp != 200)90throw new RuntimeException("Failed: Part 1, Response code is not 200: " + resp);9192System.out.println("Response code from Part 1 = 200 OK");9394// Part 295URL url2 = URIBuilder.newBuilder()96.scheme("http")97.host(address.getAddress())98.port(address.getPort())99.path("/test2/")100.toURL();101102// can use the global CookieHandler used for the first test as the URL's are different103CookieHandler ch = CookieHandler.getDefault();104Map<String,List<String>> header = new HashMap<String,List<String>>();105List<String> values = new LinkedList<String>();106values.add("Test2Cookie=\"TEST2\"; path=\"/test2/\"");107header.put("Set-Cookie2", values);108109// preload the CookieHandler with a cookie for our URL110// so that it will be sent during the first request111ch.put(url2.toURI(), header);112113uc = (HttpURLConnection)url2.openConnection();114resp = uc.getResponseCode();115if (resp != 200)116throw new RuntimeException("Failed: Part 2, Response code is not 200: " + resp);117118System.out.println("Response code from Part 2 = 200 OK");119120} finally {121httpServer.stop(1);122executorService.shutdown();123}124}125126/**127* Http Server128*/129public void startHttpServer() throws IOException {130InetAddress loopback = InetAddress.getLoopbackAddress();131httpServer = HttpServer.create(new InetSocketAddress(loopback, 0), 0);132133// create HttpServer context for Part 1.134HttpContext ctx = httpServer.createContext("/test/", new MyHandler());135ctx.setAuthenticator( new MyBasicAuthenticator("foo"));136// CookieFilter needs to be executed before Authenticator.137ctx.getFilters().add(0, new CookieFilter());138139// create HttpServer context for Part 2.140HttpContext ctx2 = httpServer.createContext("/test2/", new MyHandler2());141ctx2.setAuthenticator( new MyBasicAuthenticator("foobar"));142143executorService = Executors.newCachedThreadPool();144httpServer.setExecutor(executorService);145httpServer.start();146}147148class MyHandler implements HttpHandler {149public void handle(HttpExchange t) throws IOException {150InputStream is = t.getRequestBody();151Headers reqHeaders = t.getRequestHeaders();152Headers resHeaders = t.getResponseHeaders();153while (is.read () != -1) ;154is.close();155156if (!reqHeaders.containsKey("Authorization"))157t.sendResponseHeaders(400, -1);158159List<String> cookies = reqHeaders.get("Cookie");160if (cookies != null) {161for (String str : cookies) {162if (str.equals("Customer=WILE_E_COYOTE"))163t.sendResponseHeaders(200, -1);164}165}166t.sendResponseHeaders(400, -1);167}168}169170class MyHandler2 implements HttpHandler {171public void handle(HttpExchange t) throws IOException {172InputStream is = t.getRequestBody();173Headers reqHeaders = t.getRequestHeaders();174Headers resHeaders = t.getResponseHeaders();175while (is.read () != -1) ;176is.close();177178if (!reqHeaders.containsKey("Authorization"))179t.sendResponseHeaders(400, -1);180181List<String> cookies = reqHeaders.get("Cookie");182183// there should only be one Cookie header184if (cookies != null && (cookies.size() == 1)) {185t.sendResponseHeaders(200, -1);186}187t.sendResponseHeaders(400, -1);188}189}190191class MyAuthenticator extends java.net.Authenticator {192public PasswordAuthentication getPasswordAuthentication () {193return new PasswordAuthentication("tester", "passwd".toCharArray());194}195}196197class MyBasicAuthenticator extends BasicAuthenticator198{199public MyBasicAuthenticator(String realm) {200super(realm);201}202203public boolean checkCredentials (String username, String password) {204return username.equals("tester") && password.equals("passwd");205}206}207208class CookieFilter extends Filter209{210public void doFilter(HttpExchange t, Chain chain) throws IOException211{212Headers resHeaders = t.getResponseHeaders();213Headers reqHeaders = t.getRequestHeaders();214215if (!reqHeaders.containsKey("Authorization"))216resHeaders.set("Set-Cookie2", "Customer=\"WILE_E_COYOTE\"; path=\"/test/\"");217218chain.doFilter(t);219}220221public void destroy(HttpContext c) { }222223public void init(HttpContext c) { }224225public String description() {226return new String("Filter for setting a cookie for requests without an \"Authorization\" header.");227}228}229}230231232