use of io.vertx.core.http.Cookie in project incubator-servicecomb-java-chassis by apache.
the class CookieAccessItem method appendServerFormattedItem.
@Override
public void appendServerFormattedItem(ServerAccessLogEvent accessLogEvent, StringBuilder builder) {
Map<String, Cookie> cookieMap = accessLogEvent.getRoutingContext().cookieMap();
if (null == cookieMap) {
builder.append(RESULT_NOT_FOUND);
return;
}
for (Cookie cookie : cookieMap.values()) {
if (varName.equals(cookie.getName())) {
builder.append(cookie.getValue());
return;
}
}
builder.append(RESULT_NOT_FOUND);
}
use of io.vertx.core.http.Cookie in project vert.x by eclipse.
the class CookieJarTest method testFilterByUniqueId.
@Test
public void testFilterByUniqueId() {
CookieJar jar = new CookieJar();
jar.add(new CookieImpl("a", "a"));
jar.add((ServerCookie) new CookieImpl("a", "a").setPath("p"));
jar.add(new CookieImpl("b", "b"));
Cookie cookie = jar.get("a", null, "p");
assertNotNull(cookie);
}
use of io.vertx.core.http.Cookie in project vertx-web by vert-x3.
the class CSRFHandlerImpl method isValidRequest.
private boolean isValidRequest(RoutingContext ctx) {
/* Verifying CSRF token using "Double Submit Cookie" approach */
final Cookie cookie = ctx.request().getCookie(cookieName);
String header = ctx.request().getHeader(headerName);
if (header == null) {
// fallback to form attributes
if (((RoutingContextInternal) ctx).seenHandler(RoutingContextInternal.BODY_HANDLER)) {
header = ctx.request().getFormAttribute(headerName);
} else {
ctx.fail(new IllegalStateException("BodyHandler is required to process POST requests"));
return false;
}
}
// both the header and the cookie must be present, not null and not empty
if (header == null || cookie == null || isBlank(header)) {
ctx.fail(403, new IllegalArgumentException("Token provided via HTTP Header/Form is absent/empty"));
return false;
}
final String cookieValue = cookie.getValue();
if (cookieValue == null || isBlank(cookieValue)) {
ctx.fail(403, new IllegalArgumentException("Token provided via HTTP Header/Form is absent/empty"));
return false;
}
final byte[] headerBytes = header.getBytes(StandardCharsets.UTF_8);
final byte[] cookieBytes = cookieValue.getBytes(StandardCharsets.UTF_8);
// Verify that token from header and one from cookie are the same
if (!MessageDigest.isEqual(headerBytes, cookieBytes)) {
ctx.fail(403, new IllegalArgumentException("Token provided via HTTP Header and via Cookie are not equal"));
return false;
}
final Session session = ctx.session();
if (session != null) {
// get the token from the session
String sessionToken = session.get(headerName);
if (sessionToken != null) {
// attempt to parse the value
int idx = sessionToken.indexOf('/');
if (idx != -1 && session.id() != null && session.id().equals(sessionToken.substring(0, idx))) {
String challenge = sessionToken.substring(idx + 1);
// the challenge must match the user-agent input
if (!MessageDigest.isEqual(challenge.getBytes(StandardCharsets.UTF_8), headerBytes)) {
ctx.fail(403, new IllegalArgumentException("Token has been used or is outdated"));
return false;
}
} else {
ctx.fail(403, new IllegalArgumentException("Token has been issued for a different session"));
return false;
}
} else {
ctx.fail(403, new IllegalArgumentException("No Token has been added to the session"));
return false;
}
}
String[] tokens = header.split("\\.");
if (tokens.length != 3) {
ctx.fail(403);
return false;
}
byte[] saltPlusToken = (tokens[0] + "." + tokens[1]).getBytes(StandardCharsets.US_ASCII);
synchronized (mac) {
saltPlusToken = mac.doFinal(saltPlusToken);
}
final byte[] signature = base64UrlEncode(saltPlusToken).getBytes(StandardCharsets.US_ASCII);
if (!MessageDigest.isEqual(signature, tokens[2].getBytes(StandardCharsets.US_ASCII))) {
ctx.fail(403, new IllegalArgumentException("Token signature does not match"));
return false;
}
// this token has been used and we discard it to avoid replay attacks
if (session != null) {
session.remove(headerName);
}
final long ts = parseLong(tokens[1]);
if (ts == -1) {
ctx.fail(403);
return false;
}
// validate validity
if (System.currentTimeMillis() > ts + timeout) {
ctx.fail(403, new IllegalArgumentException("CSRF validity expired"));
return false;
}
return true;
}
use of io.vertx.core.http.Cookie in project vertx-web by vert-x3.
the class SessionHandlerImpl method flush.
private SessionHandler flush(RoutingContext context, boolean skipCrc, boolean ignoreStatus, Handler<AsyncResult<Void>> handler) {
final boolean sessionUsed = context.isSessionAccessed();
final Session session = context.session();
if (session == null) {
// No session in context
handler.handle(Future.succeededFuture());
return this;
}
if (!session.isDestroyed()) {
final int currentStatusCode = context.response().getStatusCode();
// Store the session (only and only if there was no error)
if (ignoreStatus || (currentStatusCode >= 200 && currentStatusCode < 400)) {
// store the current user into the session
Boolean storeUser = context.get(SESSION_STOREUSER_KEY);
if (storeUser != null && storeUser) {
// during the request the user might have been removed
if (context.user() != null) {
session.put(SESSION_USER_HOLDER_KEY, new UserHolder(context));
}
}
if (session.isRegenerated()) {
if (cookieless) {
// restore defaults
session.setAccessed();
} else {
// the session cookie needs to be updated to the new id
final Cookie cookie = sessionCookie(context, session);
// restore defaults
session.setAccessed();
cookie.setValue(session.value());
setCookieProperties(cookie, false);
}
// we must invalidate the old id
sessionStore.delete(session.oldId(), delete -> {
if (delete.failed()) {
handler.handle(Future.failedFuture(delete.cause()));
} else {
// we must wait for the result of the previous call in order to save the new one
sessionStore.put(session, put -> {
if (put.failed()) {
handler.handle(Future.failedFuture(put.cause()));
} else {
context.put(SESSION_FLUSHED_KEY, true);
if (session instanceof SessionInternal) {
((SessionInternal) session).flushed(skipCrc);
}
handler.handle(Future.succeededFuture());
}
});
}
});
} else if (!lazySession || sessionUsed) {
if (!cookieless) {
// if lazy mode activated, no need to store the session nor to create the session cookie if not used.
sessionCookie(context, session);
}
session.setAccessed();
sessionStore.put(session, put -> {
if (put.failed()) {
handler.handle(Future.failedFuture(put.cause()));
} else {
context.put(SESSION_FLUSHED_KEY, true);
if (session instanceof SessionInternal) {
((SessionInternal) session).flushed(skipCrc);
}
handler.handle(Future.succeededFuture());
}
});
} else {
// No-Op, just accept that the store skipped
handler.handle(Future.succeededFuture());
}
} else {
// No-Op, just accept that the store skipped
handler.handle(Future.succeededFuture());
}
} else {
if (!cookieless) {
// invalidate the cookie as the session has been destroyed
final Cookie expiredCookie = context.response().removeCookie(sessionCookieName);
if (expiredCookie != null) {
setCookieProperties(expiredCookie, true);
}
}
// the old id must also be removed
if (session.isRegenerated()) {
sessionStore.delete(session.oldId(), delete -> {
if (delete.failed()) {
handler.handle(Future.failedFuture(delete.cause()));
} else {
// delete from the storage
sessionStore.delete(session.id(), delete2 -> {
if (delete2.failed()) {
handler.handle(Future.failedFuture(delete2.cause()));
} else {
context.put(SESSION_FLUSHED_KEY, true);
handler.handle(Future.succeededFuture());
}
});
}
});
} else {
// delete from the storage
sessionStore.delete(session.id(), delete -> {
if (delete.failed()) {
handler.handle(Future.failedFuture(delete.cause()));
} else {
context.put(SESSION_FLUSHED_KEY, true);
handler.handle(Future.succeededFuture());
}
});
}
}
return this;
}
use of io.vertx.core.http.Cookie in project vertx-web by vert-x3.
the class CookieHandlerTest method testGetCookies.
@Test
public void testGetCookies() throws Exception {
router.route().handler(rc -> {
assertEquals(3, rc.request().cookieCount());
Map<String, Cookie> cookies = rc.request().cookieMap();
assertTrue(cookies.containsKey("foo"));
assertTrue(cookies.containsKey("wibble"));
assertTrue(cookies.containsKey("plop"));
Cookie removed = rc.response().removeCookie("foo");
cookies = rc.request().cookieMap();
// removed cookies, need to be sent back with an expiration date
assertTrue(cookies.containsKey("foo"));
assertTrue(cookies.containsKey("wibble"));
assertTrue(cookies.containsKey("plop"));
rc.response().end();
});
testRequest(HttpMethod.GET, "/", req -> req.headers().set("Cookie", "foo=bar; wibble=blibble; plop=flop"), resp -> {
List<String> cookies = resp.headers().getAll("set-cookie");
// the expired cookie must be sent back
assertEquals(1, cookies.size());
assertTrue(cookies.get(0).contains("Max-Age=0"));
assertTrue(cookies.get(0).contains("Expires="));
}, 200, "OK", null);
}
Aggregations