/** * 从Http Cookie中获取用户Id * * @param data * @return */ public static final PushUser getUser(HandshakeData data) { String _cookie = data.getSingleHeader(HttpHeaders.Names.COOKIE); if (_cookie != null) { Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(_cookie); for (Cookie cookie : cookies) { if (TokenManager.LOGIN_COOKIE_NAME.equals(cookie.name())) { String value = cookie.value(); if (value != null) { return getUserIdFromCookie(value); } } } } return null; }
@Override public void onRequestReceived(ChannelHandlerContext ctx, HttpRequest request) { HttpSessionThreadLocal.unset(); Collection<Cookie> cookies = Utils.getCookies(HttpSessionImpl.SESSION_ID_KEY, request); if (cookies != null) { for (Cookie cookie : cookies) { String jsessionId = cookie.value(); HttpSession s = HttpSessionThreadLocal.getSessionStore().findSession(jsessionId); if (s != null) { HttpSessionThreadLocal.set(s); this.sessionRequestedByCookie = true; break; } } } }
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; }
public static <T> BaseResponseInfo<T> createNewBaseResponseInfoForTesting(Integer httpStatusCode, HttpHeaders headers, String desiredContentWriterMimeType, Charset desiredContentWriterEncoding, Set<Cookie> cookies, boolean preventCompressedOutput) { return new BaseResponseInfo<T>(httpStatusCode, headers, desiredContentWriterMimeType, desiredContentWriterEncoding, cookies, preventCompressedOutput) { @Override public boolean isChunkedResponse() { throw new UnsupportedOperationException("not implemented, don't call me during the test"); } @Override public T getContentForFullResponse() { throw new UnsupportedOperationException("not implemented, don't call me during the test"); } @Override public void setContentForFullResponse(T contentForFullResponse) { throw new UnsupportedOperationException("not implemented, don't call me during the test"); } }; }
@Test public void uber_constructor_for_full_response_sets_fields_as_expected() { // given int httpStatusCode = 200; HttpHeaders headers = new DefaultHttpHeaders(); String mimeType = "text/text"; Charset contentCharset = CharsetUtil.UTF_8; Set<Cookie> cookies = Sets.newHashSet(new DefaultCookie("key1", "val1"), new DefaultCookie("key2", "val2")); boolean preventCompressedResponse = true; // when BaseResponseInfo<?> responseInfo = createNewBaseResponseInfoForTesting(httpStatusCode, headers, mimeType, contentCharset, cookies, preventCompressedResponse); // then assertThat(responseInfo.getHttpStatusCode(), is(httpStatusCode)); assertThat(responseInfo.getHeaders(), is(headers)); assertThat(responseInfo.getDesiredContentWriterMimeType(), is(mimeType)); assertThat(responseInfo.getDesiredContentWriterEncoding(), is(contentCharset)); assertThat(responseInfo.getCookies(), is(cookies)); assertThat(responseInfo.getUncompressedRawContentLength(), nullValue()); assertThat(responseInfo.isPreventCompressedOutput(), is(preventCompressedResponse)); assertThat(responseInfo.isResponseSendingStarted(), is(false)); assertThat(responseInfo.isResponseSendingLastChunkSent(), is(false)); }
@Test public void extractCookies_works_if_cookies_defined_in_headers() { // given Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString()); Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString()); HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2)); HttpRequest nettyRequestMock = mock(HttpRequest.class); doReturn(headers).when(nettyRequestMock).headers(); // when Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock); // then assertThat(extractedCookies.contains(cookie1), is(true)); assertThat(extractedCookies.contains(cookie2), is(true)); }
@Test public void extractCookies_works_if_cookies_defined_in_trailing_headers() { // given Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString()); Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString()); HttpHeaders trailingHeaders = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2)); FullHttpRequest nettyRequestMock = mock(FullHttpRequest.class); doReturn(new DefaultHttpHeaders()).when(nettyRequestMock).headers(); doReturn(trailingHeaders).when(nettyRequestMock).trailingHeaders(); // when Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock); // then assertThat(extractedCookies.contains(cookie1), is(true)); assertThat(extractedCookies.contains(cookie2), is(true)); }
@Test public void extractCookies_handles_cookie_values_leniently() { // given //these are cookie values seen in the wild... Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), "2094%3Az%7C2021%3Ab"); Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), "geoloc=cc=US,rc=OR,tp=vhigh,tz=PST,la=45.4978,lo=-122.6937,bw=5000"); Cookie cookie3 = new DefaultCookie(UUID.randomUUID().toString(), "\"dm=n.com&si=27431295-a282-4745-8cd5-542e7fce" + "429e&ss=1477551008358&sl=76&tt=437632&obo=12&sh=1477552753923%3D76%3A12%3A437632%2C1477552698670%3D75%3" + "A12%3A429879%2C1477552677137%3D74%3A12%3A426596%2C1477552672564%3D73%3A12%3A425585%2C1477552669893%3D72" + "%3A12%3A423456&bcn=%2F%2F3408178b.mpstat.us%2F&ld=1477552753923&r=http%3A%2F%2Fwww.nike.com%2Fbe%2Fde_de%" + "2F&ul=1477552756811\""); HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2, cookie3)); HttpRequest nettyRequestMock = mock(HttpRequest.class); doReturn(headers).when(nettyRequestMock).headers(); // when Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock); // then assertThat(extractedCookies.contains(cookie1), is(true)); assertThat(extractedCookies.contains(cookie2), is(true)); assertThat(extractedCookies.contains(cookie3), is(true)); }
public static HttpResponse createServerDefault(String requestCookie) { HttpResponse ret = new HttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer()); ret.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8"); if (requestCookie == null) { return ret; } Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(requestCookie); if (cookies.isEmpty()) { return ret; } // Reset the cookies if necessary. for (Cookie cookie : cookies) { ret.headers().add(HttpHeaderNames.SET_COOKIE, ClientCookieEncoder.STRICT.encode(cookie)); } return ret; }
protected void captureRequestCookies(HttpRequest httpRequest) { Log.e("InnerHandle", "captureRequestCookies " + harEntry.getId()); String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE); if (cookieHeader == null) { return; } Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader); for (Cookie cookie : cookies) { HarCookie harCookie = new HarCookie(); harCookie.setName(cookie.name()); harCookie.setValue(cookie.value()); harRequest.getRequest().getCookies().add(harCookie); harRequest.addHeader(cookie.name(), cookie.value()); } }
public static FullHttpRequest makeEppHttpRequest( String content, String host, String path, String accessToken, String sslClientCertificateHash, String serverHostname, String clientAddress, Cookie... cookies) { FullHttpRequest request = makeHttpPostRequest(content, host, path); request .headers() .set(HttpHeaderNames.AUTHORIZATION, "Bearer " + accessToken) .set(HttpHeaderNames.CONTENT_TYPE, EPP_CONTENT_TYPE) .set(HttpHeaderNames.ACCEPT, EPP_CONTENT_TYPE) .set(SSL_CLIENT_CERTIFICATE_HASH_FIELD, sslClientCertificateHash) .set(REQUESTED_SERVERNAME_VIA_SNI_FIELD, serverHostname) .set(FORWARDED_FOR_FIELD, clientAddress); if (cookies.length != 0) { request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(cookies)); } return request; }
@Test public void testSuccess_setCookies() throws Exception { setHandshakeSuccess(); // First inbound message is hello. channel.readInbound(); String responseContent = "<epp>response</epp>"; Cookie cookie1 = new DefaultCookie("name1", "value1"); Cookie cookie2 = new DefaultCookie("name2", "value2"); channel.writeOutbound( makeEppHttpResponse(responseContent, HttpResponseStatus.OK, cookie1, cookie2)); ByteBuf response = channel.readOutbound(); assertThat(response).isEqualTo(Unpooled.wrappedBuffer(responseContent.getBytes(UTF_8))); String requestContent = "<epp>request</epp>"; channel.writeInbound(Unpooled.wrappedBuffer(requestContent.getBytes(UTF_8))); FullHttpRequest request = channel.readInbound(); assertHttpRequestEquivalent(request, makeEppHttpRequest(requestContent, cookie1, cookie2)); // Nothing further to pass to the next handler. assertThat((Object) channel.readInbound()).isNull(); assertThat((Object) channel.readOutbound()).isNull(); assertThat(channel.isActive()).isTrue(); }
@Override public String extract(ObjectNode node, RakamHttpRequest request) { for (Cookie cookie : request.cookies()) { if (name.equals(cookie.name())) { // TODO fixme: the value of cookie parameter always must be String. return cookie.value(); } } if (required) { throw new HttpRequestException("'" + name + "' cookie is required.", BAD_REQUEST); } return null; }
public User getUserFromCookie(FullHttpRequest request) { String cookieString = request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { for (Cookie cookie : cookies) { if (isValid(cookie)) { String token = cookie.value(); return httpSession.get(token); } } } } return null; }
@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()); }
private CommonResponse createSession(String username, Set<String> roles, boolean ldap) throws Exception { String sessionId = new BigInteger(130, secureRandom).toString(32); ImmutableSession session = ImmutableSession.builder() .caseAmbiguousUsername(username) .ldap(ldap) .roles(roles) .lastRequest(clock.currentTimeMillis()) .build(); sessionMap.put(sessionId, session); String layoutJson = layoutService .getLayoutJson(session.createAuthentication(central, configRepository)); CommonResponse response = new CommonResponse(OK, MediaType.JSON_UTF_8, layoutJson); Cookie cookie = new DefaultCookie(configRepository.getWebConfig().sessionCookieName(), sessionId); cookie.setHttpOnly(true); cookie.setPath("/"); response.setHeader(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); purgeExpiredSessions(); auditSuccessfulLogin(username); return response; }
private List<Cookie> mapProperties(String project, User req, RakamHttpRequest request) { InetAddress socketAddress = ((InetSocketAddress) request.context().channel() .remoteAddress()).getAddress(); List<Cookie> cookies = null; BatchUserOperationRequest op = new BatchUserOperationRequest(req.api, ImmutableList.of(new BatchUserOperations(req.id, req.properties, null, null, null, null))); for (UserPropertyMapper mapper : mappers) { try { List<Cookie> map = mapper.map(project, op.data, new HttpRequestParams(request), socketAddress); if (map != null) { if (cookies == null) { cookies = new ArrayList<>(); } cookies.addAll(map); } } catch (Exception e) { LOGGER.error(e, "Error while mapping user properties in " + mapper.getClass().toString()); return null; } } return cookies; }
@Override public CompletableFuture<List<Cookie>> mapAsync(Event event, RequestParams requestParams, InetAddress sourceAddress, HttpHeaders responseHeaders) { return mapInternal(event.project(), new EventsProxy() { @Override public Event.EventContext api() { return event.api(); } @Override public String project() { return event.project(); } @Override public Iterator<EventProxy> events() { return Iterators.singletonIterator(new ListEventProxy(event)); } }, requestParams, sourceAddress, responseHeaders); }
@Override public CompletableFuture<List<Cookie>> mapAsync(EventList events, RequestParams requestParams, InetAddress sourceAddress, HttpHeaders responseHeaders) { EventsProxy eventsProxy = new EventsProxy() { @Override public Event.EventContext api() { return events.api; } @Override public String project() { return events.project; } @Override public Iterator<EventProxy> events() { return Iterators.transform(events.events.iterator(), new Function<Event, EventProxy>() { @Nullable @Override public EventProxy apply(@Nullable Event f) { return new ListEventProxy(f); } }); } }; return mapInternal(events.project, eventsProxy, requestParams, sourceAddress, responseHeaders); }
@Override public List<Cookie> map(String project, List<? extends ISingleUserBatchOperation> user, RequestParams extraProperties, InetAddress sourceAddress) { for (ISingleUserBatchOperation data : user) { if (data.getSetProperties() != null) { mapInternal(extraProperties, data.getSetProperties().get("_referrer"), data.getSetProperties().get("_host"), new MapProxyGenericRecord(data.getSetProperties())); } if (data.getSetPropertiesOnce() != null) { mapInternal(extraProperties, data.getSetPropertiesOnce().get("_referrer"), data.getSetPropertiesOnce().get("_host"), new MapProxyGenericRecord(data.getSetProperties())); } } return null; }
@Override public List<Cookie> map(Event event, RequestParams requestParams, InetAddress sourceAddress, HttpHeaders responseHeaders) { GenericRecord properties = event.properties(); if (properties.get("_user") == null) { Schema.Field user = event.properties().getSchema().getField("_user"); if (user == null) { return null; } Schema.Type type = user.schema().getTypes().get(1).getType(); Object anonymousUser = requestParams.cookies().stream() .filter(e -> e.name().equals("_anonymous_user")).findAny() .map(e -> cast(type, e.value())).orElse(generate(type)); properties.put("_user", anonymousUser); DefaultCookie cookie = new DefaultCookie("_anonymous_user", String.valueOf(anonymousUser)); cookie.setPath("/"); return ImmutableList.of(cookie); } return null; }
@Override public List<Cookie> map(String project, List<? extends ISingleUserBatchOperation> user, RequestParams requestParams, InetAddress sourceAddress) { // if (user.id == null) { // FieldType fieldType = userTypeCache.getUnchecked(project); // Schema field = AvroUtil.generateAvroSchema(fieldType); // Schema.Type type = field.getTypes().get(1).getType(); // Object anonymousUser = requestParams.cookies().stream() // .filter(e -> e.name().equals("_anonymous_user")).findAny() // .map(e -> cast(type, e.value())).orElse(generate(type)); // // user.setId(anonymousUser); // return ImmutableList.of(new DefaultCookie("_anonymous_user", String.valueOf(anonymousUser))); // } // return null; }
@Test(dataProvider = "google-ips") public void testIspEventMapper(Map<String, Object> props, InetAddress address) throws Exception { MaxmindGeoIPEventMapper mapper = new MaxmindGeoIPEventMapper(new MaxmindGeoIPModuleConfig() .setAttributes("") .setIspDatabaseUrl(new URL("https://github.com/maxmind/MaxMind-DB/raw/master/test-data/GeoIP2-ISP-Test.mmdb"))); FieldDependencyBuilder builder = new FieldDependencyBuilder(); mapper.addFieldDependency(builder); Record properties = new Record(Schema.createRecord(ImmutableList.of( new Schema.Field("_ip", Schema.create(NULL), null, null), new Schema.Field("__ip", Schema.create(STRING), null, null), new Schema.Field("_isp", Schema.create(STRING), null, null)))); props.forEach(properties::put); Event event = new Event("testproject", "testcollection", null, null, properties); List<Cookie> resp = mapper.map(event, EventMapper.RequestParams.EMPTY_PARAMS, address, null); assertTrue(resp == null); assertEquals(event.getAttribute("_isp"), "Level 3 Communications"); GenericData.get().validate(properties.getSchema(), properties); }
@Test(dataProvider = "google-ips") public void testConnectionTypeEventMapper(Map<String, Object> props, InetAddress address) throws Exception { MaxmindGeoIPEventMapper mapper = new MaxmindGeoIPEventMapper(new MaxmindGeoIPModuleConfig() .setAttributes("") .setConnectionTypeDatabaseUrl(new URL("https://github.com/maxmind/MaxMind-DB/raw/master/test-data/GeoIP2-Connection-Type-Test.mmdb"))); FieldDependencyBuilder builder = new FieldDependencyBuilder(); mapper.addFieldDependency(builder); Record properties = new Record(Schema.createRecord(ImmutableList.of( new Schema.Field("_ip", Schema.create(NULL), null, null), new Schema.Field("__ip", Schema.create(STRING), null, null), new Schema.Field("_connection_type", Schema.create(STRING), null, null)))); props.forEach(properties::put); Event event = new Event("testproject", "testcollection", null, null, properties); List<Cookie> resp = mapper.map(event, EventMapper.RequestParams.EMPTY_PARAMS, address, null); assertTrue(resp == null); // TODO: find a reliable ip that can be mapped. assertNull(event.getAttribute("connection_type")); GenericData.get().validate(properties.getSchema(), properties); }
public void start(final HyperSession parent, WritableByteChannel dest, String chanid, Map<String, Cookie> cookies, long size, long offset, final OperationCallback callback) { this.dest = dest; this.cookies = cookies; this.callback = callback; this.size = size; this.sent = offset; this.src = this.allocateChannel(parent, callback); if (this.callback.hasErrors()) { callback.complete(); return; } // send a request to get things going HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/download/" + chanid); req.headers().set(Names.HOST, parent.getInfo().getHost()); req.headers().set(Names.USER_AGENT, "DivConq HyperAPI Client 1.0"); req.headers().set(Names.CONNECTION, HttpHeaders.Values.CLOSE); req.headers().set(Names.COOKIE, ClientCookieEncoder.STRICT.encode(this.cookies.values())); // send request this.src.writeAndFlush(req); }
/** * 获取HttpRequest中的Cookies * @param request * @return */ public static Set<Cookie> getCookies(HttpRequest request){ Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } return cookies; }
/** * 设置所有的Cookie * @param request * @param response */ public static void setCookies(HttpRequest request,HttpResponse response){ Set<Cookie> cookies = getCookies(request); if (!cookies.isEmpty()) { for (Cookie cookie : cookies) { setCookie(response,cookie); } } }
/** * 添加一个Cookie * @param response response * @param name cookie名字 * @param value cookie值 * @param domain cookie所在域 * @param maxAge cookie生命周期 以秒为单位 */ public static void addCookie(HttpResponse response,String name,String value,String domain,long maxAge){ Cookie cookie = new DefaultCookie(name,value); cookie.setPath("/"); if(domain!=null && domain.trim().length()>0) { cookie.setDomain(domain); } if(maxAge>0){ cookie.setMaxAge(maxAge); } setCookie(response,cookie); }
/** * 将cookie封装到Map里面 * @param request HttpRequest * @return */ public static Map<String,Cookie> getCookieMap(HttpRequest request){ Map<String,Cookie> cookieMap = new HashMap<String,Cookie>(); Set<Cookie> cookies = getCookies(request); if(null!=cookies && !cookies.isEmpty()){ for(Cookie cookie : cookies){ cookieMap.put(cookie.name(), cookie); } } return cookieMap; }
/** * 删除一个Cookie * @param request * @param response * @param name * @return */ public static boolean deleteCookie(HttpRequest request,HttpResponse response,String name) { Cookie cookie = getCookie(request,name); if(cookie!=null){ cookie.setMaxAge(0); cookie.setPath("/"); setCookie(response,cookie); return true; } return false; }
@Override public void setCookie(Cookie cookie) { if(response==null){ response = response(); } CookieHelper.setCookie(response,cookie); }
public static final Collection<Cookie> getCookies(String name, HttpRequest request) { String cookieString = request.headers().get(COOKIE); if (cookieString != null) { List<Cookie> foundCookie = new ArrayList<Cookie>(); // 不验证name 和 value Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString); for (Cookie cookie : cookies) { if (cookie.name().equals(name)) foundCookie.add(cookie); } return foundCookie; } return null; }
public static final Collection<Cookie> getCookies(String name, HttpResponse response) { String cookieString = response.headers().get(COOKIE); if (cookieString != null) { List<Cookie> foundCookie = new ArrayList<Cookie>(); // 不验证name 和 value Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString); for (Cookie cookie : cookies) { if (cookie.name().equals(name)) foundCookie.add(cookie); } return foundCookie; } return null; }
@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()); }
public static Cookie createCookie(String name, String value, String domain, String path) { Cookie cookie = new DefaultCookie(name, value); cookie.setDomain(domain); cookie.setPath(path); return cookie; }
@Override public void handle(ServerWebSocket serverWebSocket) { String basePath = Optional.ofNullable(mountPoint) .map(m -> m.substring(0, m.lastIndexOf('/')) ) .orElse(""); if (!serverWebSocket.path().startsWith(basePath + "/PUSH")) { serverWebSocket.reject(); } String cookieHeader = serverWebSocket.headers().get(COOKIE); if (cookieHeader != null) { Optional<String> sessionId = ServerCookieDecoder.STRICT.decode(cookieHeader).stream() .filter(cookie -> cookieName.equals(cookie.name())) .findFirst().map(Cookie::value); if (sessionId.isPresent()) { sessionId.ifPresent(sid -> sessionStore.get(sid, event -> { Session session = null; if (event.succeeded()) { session = event.result(); } next.accept(serverWebSocket, session); } )); return; } } next.accept(serverWebSocket, null); }
@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; }
/** * The "populate everything" constructor. It's recommended that you use the {@link ChunkedResponseInfoBuilder} * instead. */ public ChunkedResponseInfo(Integer httpStatusCode, HttpHeaders headers, String desiredContentWriterMimeType, Charset desiredContentWriterEncoding, Set<Cookie> cookies, boolean preventCompressedOutput) { super(httpStatusCode, headers, desiredContentWriterMimeType, desiredContentWriterEncoding, cookies, preventCompressedOutput); }
/** * The "populate everything" constructor. It's recommended that you use the {@link FullResponseInfoBuilder} instead. */ public FullResponseInfo(T contentForFullResponse, Integer httpStatusCode, HttpHeaders headers, String desiredContentWriterMimeType, Charset desiredContentWriterEncoding, Set<Cookie> cookies, boolean preventCompressedOutput) { super(httpStatusCode, headers, desiredContentWriterMimeType, desiredContentWriterEncoding, cookies, preventCompressedOutput); this.contentForFullResponse = contentForFullResponse; }