@Test public void testCookieFields() throws Exception { Cookie cookie = Cookie.cookie("foo", "bar"); assertEquals("foo", cookie.getName()); assertEquals("bar", cookie.getValue()); assertEquals("foo=bar", cookie.encode()); assertNull(cookie.getPath()); cookie.setPath("/somepath"); assertEquals("/somepath", cookie.getPath()); assertEquals("foo=bar; Path=/somepath", cookie.encode()); assertNull(cookie.getDomain()); cookie.setDomain("foo.com"); assertEquals("foo.com", cookie.getDomain()); assertEquals("foo=bar; Path=/somepath; Domain=foo.com", cookie.encode()); long maxAge = 30 * 60; cookie.setMaxAge(maxAge); long now = System.currentTimeMillis(); String encoded = cookie.encode(); int startPos = encoded.indexOf("Expires="); int endPos = encoded.indexOf(';', startPos); String expiresDate = encoded.substring(startPos + 8, endPos); Date d = dateTimeFormat.parse(expiresDate); assertTrue(d.getTime() - now >= maxAge); cookie.setMaxAge(Long.MIN_VALUE); cookie.setSecure(true); assertEquals("foo=bar; Path=/somepath; Domain=foo.com; Secure", cookie.encode()); cookie.setHttpOnly(true); assertEquals("foo=bar; Path=/somepath; Domain=foo.com; Secure; HTTPOnly", cookie.encode()); }
cookie.setValue(session.value()).setPath("/").setSecure(sessionCookieSecure) .setHttpOnly(sessionCookieHttpOnly);
@Override public Cookie[] getCookies() { if (cookies == null) { Set<io.vertx.ext.web.Cookie> vertxCookies = context.cookies(); Cookie tmpCookies[] = new Cookie[vertxCookies.size()]; int idx = 0; for (io.vertx.ext.web.Cookie oneVertxCookie : vertxCookies) { Cookie cookie = new Cookie(oneVertxCookie.getName(), oneVertxCookie.getValue()); tmpCookies[idx] = cookie; idx++; } cookies = tmpCookies; } return cookies; }
private void createNewSession(RoutingContext context) { Session session = sessionStore.createSession(sessionTimeout, minLength); context.setSession(session); Cookie cookie = Cookie.cookie(sessionCookieName, session.value()); cookie.setPath(sessionCookiePath); cookie.setSecure(sessionCookieSecure); cookie.setHttpOnly(sessionCookieHttpOnly); // Don't set max age - it's a session cookie context.addCookie(cookie); addStoreSessionHandler(context); } }
public Handler<RoutingContext> loginStatusHandler() { return rc -> { AuthenticatedUser user = AuthenticatedUser.from(rc); if (user != null) { rc.response().end(new JsonObject() .put("authenticated", true) // TODO issuer; acting principal; authority sets .put("accountId", user.getAuthenticatedAs()) .put("userDisplayName", user.getFullDisplayName()).encode()); } else { QueryStringEncoder params = new QueryStringEncoder(""); params.addParam("client_id", clientId); params.addParam("response_type", "code"); params.addParam("scope", scope); params.addParam("redirect_uri", redirectUri(rc)); String state = new TokenGenerator(secureRandom).create(15); params.addParam("state", state); rc.response().headers().add(SET_COOKIE, io.vertx.ext.web.Cookie.cookie("state", state) .setHttpOnly(true) .setSecure(redirectUri(rc).startsWith("https")).encode()); rc.response().end(new JsonObject() .put("authenticated", false) .put("loginUrl", authUrl + params).encode()); } }; }
} else if (!xsrf.getValue().equals(xsrfHeader)) { log.debug("XSRF header did not match"); if (redirecter == null) { if (session != null && session.getValue() != null) { jwt.authenticate(new JsonObject().put("jwt", session.getValue()), r -> { if (r.succeeded()) { MetricsHandler.checkpoint(rc, "auth"); } else { MetricsHandler.checkpoint(rc, "authFail"); rc.response().headers().add(SET_COOKIE, session.setValue("").setMaxAge(0).encode()); if (mandatory) { log.debug("Access token could not be authenticated", r.cause());
private boolean validateToken(String header, Cookie cookie) { // both the header and the cookie must be present, not null and equal if (header == null || cookie == null || !header.equals(cookie.getValue())) { return false; } String[] tokens = header.split("\\."); if (tokens.length != 3) { return false; } String saltPlusToken = tokens[0] + "." + tokens[1]; String signature = BASE64.encodeToString(mac.doFinal(saltPlusToken.getBytes())); if(!signature.equals(tokens[2])) { return false; } try { // validate validity return !(System.currentTimeMillis() > Long.parseLong(tokens[1]) + timeout); } catch (NumberFormatException e) { return false; } }
if (cookie.isChanged()) { rc.response().headers().add(SET_COOKIE, cookie.encode()); params.addParam("state", state); rc.response().headers().add(SET_COOKIE, io.vertx.ext.web.Cookie.cookie("state", state) .setHttpOnly(true) .setPath(rc.mountPoint() + "/") .setSecure(redirectUri(rc).startsWith("https")).encode()); params.addParam("state", state); rc.response().headers().add(SET_COOKIE, io.vertx.ext.web.Cookie.cookie("state", state) .setHttpOnly(true) .setPath(rc.mountPoint() + "/") .setSecure(redirectUri(rc).startsWith("https")).encode()); params.addParam("state", state); rc.response().headers().add(SET_COOKIE, io.vertx.ext.web.Cookie.cookie("state", state) .setHttpOnly(true) .setPath(rc.mountPoint() + "/") .setSecure(redirectUri(rc).startsWith("https")).encode());
router.route().handler(rc -> { assertEquals(3, rc.cookieCount()); assertEquals("bar", rc.getCookie("foo").getValue()); assertEquals("blibble", rc.getCookie("wibble").getValue()); assertEquals("flop", rc.getCookie("plop").getValue()); rc.removeCookie("plop"); }); router.route().handler(rc -> { assertEquals("bar", rc.getCookie("foo").getValue()); assertEquals("blibble", rc.getCookie("wibble").getValue()); assertNotNull(rc.getCookie("plop")); rc.addCookie(Cookie.cookie("fleeb", "floob")); assertEquals(4, rc.cookieCount()); assertNull(rc.removeCookie("blarb")); assertEquals(4, rc.cookieCount()); Cookie foo = rc.getCookie("foo"); foo.setValue("blah"); rc.response().end(); });
@Override public Collection<Cookie> getRequestCookies() { return routingContext.cookies().stream().map(cookie -> { final Cookie p4jCookie = new Cookie(cookie.getName(), cookie.getValue()); p4jCookie.setDomain(cookie.getDomain()); p4jCookie.setPath(cookie.getPath()); return p4jCookie; }).collect(Collectors.toList()); }
public Handler<RoutingContext> logoutHandler() { return rc -> { if ("yes".equals(rc.request().getParam("done"))) { rc.response().setStatusCode(302).putHeader("Location", VertxBase.absoluteContext(config::getString, rc)).end(); // rc.response().end("Logout complete"); return; } QueryStringEncoder fromEnc = new QueryStringEncoder(""); fromEnc.addParam("redirect_uri", VertxBase.absolutePath(config::getString, rc) + "?done=yes"); rc.response().headers() .add(SET_COOKIE, io.vertx.ext.web.Cookie.cookie("session_token", "").setMaxAge(0).encode()) .add(SET_COOKIE, io.vertx.ext.web.Cookie.cookie("XSRF-TOKEN", "").setMaxAge(0).encode()) .add("location", logoutUrl + fromEnc); rc.response().setStatusCode(302).end(); }; }
/** * Create a new cookie * @param name the name of the cookie * @param value the cookie value * @return the cookie */ public static io.vertx.rxjava.ext.web.Cookie cookie(String name, String value) { io.vertx.rxjava.ext.web.Cookie ret = io.vertx.rxjava.ext.web.Cookie.newInstance(io.vertx.ext.web.Cookie.cookie(name, value)); return ret; }
@Override public void handle(RoutingContext context) { String cookieHeader = context.request().headers().get(COOKIE); if (cookieHeader != null) { Set<io.netty.handler.codec.http.cookie.Cookie> nettyCookies = ServerCookieDecoder.STRICT.decode(cookieHeader); for (io.netty.handler.codec.http.cookie.Cookie cookie : nettyCookies) { Cookie ourCookie = new CookieImpl(cookie); context.addCookie(ourCookie); } } context.addHeadersEndHandler(v -> { // save the cookies Set<Cookie> cookies = context.cookies(); for (Cookie cookie: cookies) { if (cookie.isChanged()) { context.response().headers().add(SET_COOKIE, cookie.encode()); } } }); context.next(); }
@Override public RoutingContext addCookie(Cookie cookie) { cookiesMap().put(cookie.getName(), cookie); return this; }
private void proxy(RoutingContext context, io.vertx.ext.web.Cookie cookie) { final String cookiePath = cookie.getPath(); String forwardedPath = context.request().getHeader(X_FORWARDED_PREFIX); if (forwardedPath != null && !forwardedPath.isEmpty()) { // remove trailing slash forwardedPath = forwardedPath.substring(0, forwardedPath.length() - (forwardedPath.endsWith("/") ? 1 : 0)); forwardedPath += cookiePath; } else { forwardedPath = cookiePath; } cookie.setPath(forwardedPath); }
@Override public Cookie removeCookie(String name, boolean invalidate) { Cookie cookie = cookiesMap().get(name); if (cookie != null) { if (invalidate && cookie.isFromUserAgent()) { // in the case the cookie was passed from the User Agent // we need to expire it and sent it back to it can be // invalidated cookie.setMaxAge(0L); } else { // this was a temporary cookie so we can safely remove it cookiesMap().remove(name); } } return cookie; }