protected HttpsURLConnection getUrlConnection(String username, String password, URL url) throws Exception { HttpsURLConnection.setDefaultSSLSocketFactory(getSSLSocketFactory()); URL loginURL = new URL(url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + "/login"); HttpsURLConnection con = (HttpsURLConnection) loginURL.openConnection(); con.setHostnameVerifier((host, session) -> true); con.setRequestMethod("GET"); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json"); con.connect(); int responseCode = con.getResponseCode(); if (401 == responseCode) { throw new UnauthorizedUserException(); } Assert.assertEquals(200, responseCode); List<String> cookies = con.getHeaderFields().get(Names.SET_COOKIE); Assert.assertEquals(1, cookies.size()); Cookie sessionCookie = ClientCookieDecoder.STRICT.decode(cookies.get(0)); Assert.assertEquals(Constants.COOKIE_NAME, sessionCookie.name()); con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty(Names.COOKIE, sessionCookie.name() + "=" + sessionCookie.value()); con.setHostnameVerifier((host, session) -> true); return con; }
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { FullHttpResponse response = (FullHttpResponse) msg; if (httpRequiresSessionId && !active) { final List<String> setCookieHeaderValues = response.headers().getAll(HttpHeaderNames.SET_COOKIE); for (String setCookieHeaderValue : setCookieHeaderValues) { final Cookie cookie = ClientCookieDecoder.LAX.decode(setCookieHeaderValue); if ("JSESSIONID".equals(cookie.name())) { this.cookie = setCookieHeaderValue; break; } } active = true; handShakeFuture.run(); } waitingGet = false; ctx.fireChannelRead(response.content()); }
@Test public void testBasicAuthentication() throws Exception { Configuration config = TestConfiguration.createMinimalConfigurationForTest(); BasicAuthLogin auth = new BasicAuthLogin(); auth.setUsername("test"); auth.setPassword("test1"); DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login"); request.content().writeBytes(JsonSerializer.getObjectMapper().writeValueAsBytes(auth)); TestHttpQueryDecoder decoder = new TestHttpQueryDecoder(config); decoder.decode(null, request, results); Assert.assertEquals(1, results.size()); Object result = results.iterator().next(); Assert.assertEquals(BasicAuthLoginRequest.class, result.getClass()); BasicAuthLoginRequestHandler handler = new BasicAuthLoginRequestHandler(config); CaptureChannelHandlerContext ctx = new CaptureChannelHandlerContext(); handler.channelRead(ctx, result); Assert.assertNotNull(ctx.msg); Assert.assertTrue(ctx.msg instanceof DefaultFullHttpResponse); DefaultFullHttpResponse response = (DefaultFullHttpResponse) ctx.msg; Assert.assertEquals(HttpResponseStatus.OK, response.getStatus()); Assert.assertTrue(response.headers().contains(Names.CONTENT_TYPE)); Assert.assertEquals(Constants.JSON_TYPE, response.headers().get(Names.CONTENT_TYPE)); Assert.assertTrue(response.headers().contains(Names.SET_COOKIE)); Cookie c = ClientCookieDecoder.STRICT.decode(response.headers().get(Names.SET_COOKIE)); Assert.assertEquals(TestConfiguration.HTTP_ADDRESS_DEFAULT, c.domain()); Assert.assertEquals(86400, c.maxAge()); Assert.assertTrue(c.isHttpOnly()); Assert.assertTrue(c.isSecure()); Assert.assertEquals(Constants.COOKIE_NAME, c.name()); UUID.fromString(c.value()); }
static Cookie fromVertxCookie(io.vertx.ext.web.Cookie cookie) { io.netty.handler.codec.http.cookie.Cookie decoded = ClientCookieDecoder.STRICT.decode(cookie.encode()); Cookie out = new Cookie(decoded.name(), decoded.value()); Optional.ofNullable(decoded.domain()).ifPresent(out::setDomain); out.setPath(decoded.path()); out.setHttpOnly(decoded.isHttpOnly()); out.setSecure(decoded.isSecure()); if (decoded.maxAge() != Long.MIN_VALUE) { out.setMaxAge((int) decoded.maxAge()); } // TODO extract other values return out; }
@Test public void testBasicAuthentication() throws Exception { Configuration config = TestConfiguration.createMinimalConfigurationForTest(); // @formatter:off String form = "{\n" + " \"username\": \"test\",\n" + " \"password\": \"test1\"\n" + "}"; // @formatter:on DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login"); request.content().writeBytes(form.getBytes()); TestHttpQueryDecoder decoder = new TestHttpQueryDecoder(config); decoder.decode(null, request, results); Assert.assertEquals(1, results.size()); Object result = results.iterator().next(); Assert.assertEquals(BasicAuthLoginRequest.class, result.getClass()); BasicAuthLoginRequestHandler handler = new BasicAuthLoginRequestHandler(config); CaptureChannelHandlerContext ctx = new CaptureChannelHandlerContext(); handler.channelRead(ctx, result); Assert.assertNotNull(ctx.msg); Assert.assertTrue(ctx.msg instanceof DefaultFullHttpResponse); DefaultFullHttpResponse response = (DefaultFullHttpResponse) ctx.msg; Assert.assertEquals(HttpResponseStatus.OK, response.getStatus()); Assert.assertTrue(response.headers().contains(Names.CONTENT_TYPE)); Assert.assertEquals(Constants.JSON_TYPE, response.headers().get(Names.CONTENT_TYPE)); Assert.assertTrue(response.headers().contains(Names.SET_COOKIE)); Cookie c = ClientCookieDecoder.STRICT.decode(response.headers().get(Names.SET_COOKIE)); Assert.assertEquals(TestConfiguration.TIMELY_HTTP_ADDRESS_DEFAULT, c.domain()); Assert.assertEquals(86400, c.maxAge()); Assert.assertTrue(c.isHttpOnly()); Assert.assertTrue(c.isSecure()); Assert.assertEquals(Constants.COOKIE_NAME, c.name()); UUID.fromString(c.value()); }
protected HttpsURLConnection getUrlConnection(String username, String password, URL url) throws Exception { HttpsURLConnection.setDefaultSSLSocketFactory(getSSLSocketFactory()); URL loginURL = new URL(url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + "/login"); HttpsURLConnection con = (HttpsURLConnection) loginURL.openConnection(); con.setHostnameVerifier((host, session) -> true); con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json"); BasicAuthLoginRequest request = new BasicAuthLoginRequest(); request.setUsername(username); request.setPassword(password); String requestJSON = JsonUtil.getObjectMapper().writeValueAsString(request); con.setRequestProperty("Content-Length", String.valueOf(requestJSON.length())); OutputStream wr = con.getOutputStream(); wr.write(requestJSON.getBytes(UTF_8)); int responseCode = con.getResponseCode(); if (401 == responseCode) { throw new UnauthorizedUserException(); } Assert.assertEquals(200, responseCode); List<String> cookies = con.getHeaderFields().get(Names.SET_COOKIE); Assert.assertEquals(1, cookies.size()); Cookie sessionCookie = ClientCookieDecoder.STRICT.decode(cookies.get(0)); Assert.assertEquals(Constants.COOKIE_NAME, sessionCookie.name()); con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty(Names.COOKIE, sessionCookie.name() + "=" + sessionCookie.value()); con.setHostnameVerifier((host, session) -> true); return con; }
protected void captureResponseCookies(HttpResponse httpResponse) { Log.e("InnerHandle", "captureResponseCookies " + harEntry.getId()); List<String> setCookieHeaders = httpResponse.headers().getAll(HttpHeaders.Names.SET_COOKIE); if (setCookieHeaders == null) { return; } for (String setCookieHeader : setCookieHeaders) { Cookie cookie = ClientCookieDecoder.LAX.decode(setCookieHeader); if (cookie == null) { return; } HarCookie harCookie = new HarCookie(); harCookie.setName(cookie.name()); harCookie.setValue(cookie.value()); // comment is no longer supported in the netty ClientCookieDecoder harCookie.setDomain(cookie.domain()); harCookie.setHttpOnly(cookie.isHttpOnly()); harCookie.setPath(cookie.path()); harCookie.setSecure(cookie.isSecure()); if (cookie.maxAge() > 0) { // use a Calendar with the current timestamp + maxAge seconds. the locale of the calendar is irrelevant, // since we are dealing with timestamps. Calendar expires = Calendar.getInstance(); // zero out the milliseconds, since maxAge is in seconds expires.set(Calendar.MILLISECOND, 0); // we can't use Calendar.add, since that only takes ints. TimeUnit.convert handles second->millisecond // overflow reasonably well by returning the result as Long.MAX_VALUE. expires.setTimeInMillis(expires.getTimeInMillis() + TimeUnit.MILLISECONDS.convert(cookie.maxAge(), TimeUnit.SECONDS)); harCookie.setExpires(expires.getTime()); } harResponse.getResponse().getCookies().add(harCookie); harResponse.addHeader(harCookie.getName(), harCookie.getValue()); } }
/** * 获得响应 cookie * * @return cookies */ public static Cookie[] getResponseCookies(NHttpResponse response) { ArrayList<Cookie> cookies = new ArrayList<Cookie>(); ClientCookieDecoder clientCookieDecoder = ClientCookieDecoder.STRICT; String[][] matchResult = NHttpTools.parseHeaders(response.response()); for (String[] strings : matchResult) { if (strings[0].equalsIgnoreCase(HttpHeaders.Names.SET_COOKIE)) { Cookie cookie = clientCookieDecoder.decode(strings[1]); cookies.add(cookie); } } return cookies.toArray(new Cookie[0]); }
private boolean cookieHeaderAlreadyExists(HttpResponse response, org.mockserver.model.Cookie cookieValue) { List<String> setCookieHeaders = response.getHeader(SET_COOKIE.toString()); for (String setCookieHeader : setCookieHeaders) { String existingCookieName = ClientCookieDecoder.LAX.decode(setCookieHeader).name(); String existingCookieValue = ClientCookieDecoder.LAX.decode(setCookieHeader).value(); if (existingCookieName.equalsIgnoreCase(cookieValue.getName().getValue()) && existingCookieValue.equalsIgnoreCase(cookieValue.getValue().getValue())) { return true; } } return false; }
private boolean cookieHeaderAlreadyExists(HttpResponse response, Cookie cookieValue) { List<String> setCookieHeaders = response.getHeader(SET_COOKIE.toString()); for (String setCookieHeader : setCookieHeaders) { String existingCookieName = ClientCookieDecoder.LAX.decode(setCookieHeader).name(); String existingCookieValue = ClientCookieDecoder.LAX.decode(setCookieHeader).value(); if (existingCookieName.equalsIgnoreCase(cookieValue.getName().getValue()) && existingCookieValue.equalsIgnoreCase(cookieValue.getValue().getValue())) { return true; } } return false; }
public void handleHttpRequest(ChannelHandlerContext ctx, HttpObject obj) throws Exception { Logger.debug("got http message " + obj); if (obj instanceof HttpContent) { if (this.decoder == null) { Logger.error("Got chunk before getting headers!"); return; } this.decoder.offer((HttpContent)obj); return; } if (!(obj instanceof HttpResponse)) { Logger.error("Got unknown instead of headers!"); return; } HttpResponse resp = (HttpResponse) obj; // keep the cookies - especially Session! List<String> cookies = resp.headers().getAll(Names.SET_COOKIE); for (String cookie : cookies) { Cookie c = ClientCookieDecoder.STRICT.decode(cookie); this.cookies.put(c.name(), c); } this.decoder = new HttpBodyRequestDecoder(4096 * 1024, new IBodyCallback() { @Override public void ready(Memory mem) { // if response is empty ignore if (mem.getLength() == 0) return; FuncResult<CompositeStruct> pres = CompositeParser.parseJson(mem); if (pres.hasErrors()) { Logger.error("Error parsing response JSON!"); return; } CompositeStruct croot = pres.getResult(); if ((croot == null) || !(croot instanceof RecordStruct)) { Logger.error("Error parsing response JSON!"); return; } ClientHandler.this.session.receiveMessage(MessageUtil.fromRecord((RecordStruct) croot)); } @Override public void fail() { Logger.error("Failure processing http response"); } }); }
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { //System.out.println("download client got object: " + msg.getClass().getName()); if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; try { //System.out.println("client offered content"); int camt = chunk.content().readableBytes(); for (ByteBuffer bb : chunk.content().nioBuffers()) this.dest.write(bb); this.sent += camt; this.callback.getContext().setAmountCompleted((int)(this.sent * 100 / this.size)); // final only if not canceled if (chunk instanceof LastHttpContent) this.finish(); } catch (IOException x) { this.callback.error(1, "Failed download because of local io error: " + x); this.finish(); } return; } if (!(msg instanceof HttpResponse)) { System.out.println("Got unknown instead of headers!"); // TODO return; } HttpResponse resp = (HttpResponse) msg; // keep the cookies - especially Session! List<String> cookies = resp.headers().getAll(Names.SET_COOKIE); for (String cookie : cookies) { Cookie c = ClientCookieDecoder.STRICT.decode(cookie); this.cookies.put(c.name(), c); } // TODO if error response then cancel otherwise // ignore we don't care //System.out.println("Got response: " + resp); }
/** * Save session cookies from the HTTP response header to the cookie store. * * <p>Multiple cookies are </b>not</b> folded in to one {@code Set-Cookie} header per RFC 6265. * * @see <a href="https://tools.ietf.org/html/rfc6265#section-3">RFC 6265 3.Overview</a> */ private void saveCookies(FullHttpResponse response) { for (String cookieString : response.headers().getAll(HttpHeaderNames.SET_COOKIE)) { Cookie cookie = ClientCookieDecoder.STRICT.decode(cookieString); cookieStore.put(cookie.name(), cookie); } }