Java Code Examples for io.vertx.ext.web.RoutingContext#getCookie()

The following examples show how to use io.vertx.ext.web.RoutingContext#getCookie() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CookieParamInjector.java    From nubes with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolve(RoutingContext context, CookieValue annotation, String paramName, Class<?> resultClass) {
  String cookieName = annotation.value();
  if ("".equals(cookieName)) {
    cookieName = paramName;
  }
  Cookie cookie = context.getCookie(cookieName);
  if (resultClass.equals(Cookie.class) && cookie != null) {
    return cookie;
  } else if (resultClass.equals(String.class) && cookie != null) {
    return cookie.getValue();
  } else if (cookie == null) {
    DefaultErrorHandler.badRequest(context, "Cookie " + cookieName + " must be set");
  }
  return null;
}
 
Example 2
Source File: WebHelper.java    From nassh-relay with GNU General Public License v2.0 6 votes vote down vote up
public static AuthSession validateCookie(final RoutingContext context) {
    final Cookie cookie = context.getCookie(Constants.SESSIONCOOKIE);
    if (cookie == null) {
        return null;
    }
    final UUID sessioncookie = UUID.fromString(cookie.getValue());
    final AuthSession session = AuthSessionManager.getSession(sessioncookie);
    if (session == null) {
        return null;
    }
    final String id = session.get("id");
    if (id != null) {
        return session;
    }
    return null;
}
 
Example 3
Source File: FormAuthenticationMechanism.java    From quarkus with Apache License 2.0 5 votes vote down vote up
protected void handleRedirectBack(final RoutingContext exchange) {
    Cookie redirect = exchange.getCookie(locationCookie);
    String location;
    if (redirect != null) {
        location = redirect.getValue();
        exchange.response().addCookie(redirect.setMaxAge(0));
    } else {
        location = exchange.request().scheme() + "://" + exchange.request().host() + landingPage;
    }
    exchange.response().setStatusCode(302);
    exchange.response().headers().add(HttpHeaderNames.LOCATION, location);
    exchange.response().end();
}
 
Example 4
Source File: CookieAttribute.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public String readAttribute(final RoutingContext exchange) {
    Cookie cookie = exchange.getCookie(cookieName);
    if (cookie == null) {
        return null;
    }
    return cookie.getValue();
}
 
Example 5
Source File: SessionHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private String getSessionId(RoutingContext  context) {
  if (cookieless) {
    // cookieless sessions store the session on the path or the request
    // a session is identified by a sequence of characters between braces
    String path = context.normalizedPath();
    int s = -1;
    int e = -1;
    for (int i = 0; i < path.length(); i++) {
      if (path.charAt(i) == '(') {
        s = i + 1;
        continue;
      }
      if (path.charAt(i) == ')') {
        // if not open parenthesis yet
        // this is a false end, continue looking
        if (s != -1) {
          e = i;
          break;
        }
      }
    }
    if (s != -1 && e != -1 && s < e) {
      return path.substring(s, e);
    }
  } else {
    Cookie cookie = context.getCookie(sessionCookieName);
    if (cookie != null) {
      // Look up sessionId
      return cookie.getValue();
    }
  }

  return null;
}
 
Example 6
Source File: SessionHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Cookie sessionCookie(final RoutingContext context, final Session session) {
  Cookie cookie = context.getCookie(sessionCookieName);
  if (cookie != null) {
    return cookie;
  }
  cookie = Cookie.cookie(sessionCookieName, session.value());
  cookie.setPath(sessionCookiePath);
  cookie.setSecure(sessionCookieSecure);
  cookie.setHttpOnly(sessionCookieHttpOnly);
  cookie.setSameSite(cookieSameSite);
  // Don't set max age - it's a session cookie
  context.addCookie(cookie);
  return cookie;
}
 
Example 7
Source File: PersistentLoginManager.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public RestoreResult restore(RoutingContext context) {
    Cookie existing = context.getCookie(cookieName);
    // If there is no credential cookie, we have nothing to restore.
    if (existing == null) {
        // Enforce new login.
        return null;
    }
    String val = existing.getValue();
    try {
        Cipher cipher = Cipher.getInstance(ENC_ALGORITHM);
        ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getDecoder().decode(val.getBytes(StandardCharsets.UTF_8)));
        int ivLength = byteBuffer.get();
        byte[] iv = new byte[ivLength];
        byteBuffer.get(iv);
        byte[] encrypted = new byte[byteBuffer.remaining()];
        byteBuffer.get(encrypted);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(ENC_TAG_LENGTH, iv));
        String result = new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
        int sep = result.indexOf(":");
        // If parsing fails, something is wrong and we need to enforce a new login.
        if (sep == -1) {
            // Enforce new login.
            log.debugf("%s cookie parsing failed. Is encryption-key set for all instances?", cookieName);
            return null;
        }
        long expireIdle = Long.parseLong(result.substring(0, sep));
        long now = System.currentTimeMillis();
        log.debugf("Current time: %s, Expire idle timeout: %s, expireIdle - now is: %d - %d = %d",
                new Date(now).toString(), new Date(expireIdle).toString(), expireIdle, now, expireIdle - now);
        // We don't attempt renewal, idle timeout already expired.
        if (now > expireIdle) {
            // Enforce new login.
            return null;
        }
        boolean newCookieNeeded = (timeoutMillis - (expireIdle - now)) > newCookieIntervalMillis;
        log.debugf("Is new cookie needed? ( %d - ( %d - %d)) > %d : %b", timeoutMillis, expireIdle, now,
                newCookieIntervalMillis, newCookieNeeded);
        return new RestoreResult(result.substring(sep + 1), newCookieNeeded);
    } catch (Exception e) {
        log.debug("Failed to restore persistent user session", e);
        return null;
    }
}
 
Example 8
Source File: SessionHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    if (nagHttps && log.isDebugEnabled()) {
        String uri = context.request().absoluteURI();
        if (!uri.startsWith("https:")) {
            log.debug(
                    "Using session cookies without https could make you susceptible to session hijacking: " + uri);
        }
    }

    // Look for existing session cookie
    Cookie cookie = context.getCookie(sessionCookieName);
    if (cookie != null) {
        // Look up session
        String sessionID = cookie.getValue();
        if (sessionID != null && sessionID.length() > minLength) {
            // we passed the OWASP min length requirements
            getSession(context.vertx(), sessionID, res -> {
                if (res.succeeded()) {
                    Session session = res.result();
                    if (session != null) {
                        context.setSession(session);
                        // attempt to load the user from the session if auth provider is known
                        if (authProvider != null) {
                            UserHolder holder = session.get(SESSION_USER_HOLDER_KEY);
                            if (holder != null) {
                                User user = null;
                                RoutingContext prevContext = holder.context;
                                if (prevContext != null) {
                                    user = prevContext.user();
                                } else if (holder.user != null) {
                                    user = holder.user;
                                    user.setAuthProvider(authProvider);
                                    holder.context = context;
                                    holder.user = null;
                                }
                                holder.context = context;
                                if (user != null) {
                                    context.setUser(user);
                                }
                            }
                            addStoreSessionHandler(context, holder == null);
                        } else {
                            // never store user as there's no provider for auth
                            addStoreSessionHandler(context, false);
                        }

                    } else {
                        // Cannot find session - either it timed out, or was explicitly destroyed at the
                        // server side on a
                        // previous request.

                        // OWASP clearly states that we shouldn't recreate the session as it allows
                        // session fixation.
                        // create a new anonymous session.
                        createNewSession(context);
                    }
                } else {
                    context.fail(res.cause());
                }
                context.next();
            });
            return;
        }
    }
    // requirements were not met, so a anonymous session is created.
    createNewSession(context);
    context.next();
}
 
Example 9
Source File: CookiePostHandler.java    From nassh-relay with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    logger.debug("got request");
    final HttpServerRequest request = context.request();
    final HttpServerResponse response = context.response();
    response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
    response.putHeader("Pragma", "no-cache");
    response.putHeader("Content-Type", "no-cache");
    response.putHeader("Content-Type", "application/json");
    final Cookie cookie = context.getCookie(Constants.SESSIONCOOKIE);
    UUID sessioncookie;
    if (cookie == null) {
        sessioncookie = null;
    } else {
        sessioncookie = UUID.fromString(cookie.getValue());
    }
    final AuthSession session = AuthSessionManager.getSession(sessioncookie);
    if (session == null) {
        response.setStatusCode(403);
        response.end("\"Invalid session cookie.\"");
        return;
    }
    final String token = session.get("token");
    final String state = session.get("state");
    if (token != null) {
        response.setStatusCode(200);
        response.end("\"Current user is already connected.\"");
        return;
    }
    if (!request.params().contains("state") || !request.params().get("state").equals(state)) {
        response.setStatusCode(403);
        response.end("\"Invalid state parameter.\"");
        return;
    }
    request.bodyHandler(body -> {
        final JsonObject tokenConfig = new JsonObject()
            .put("code", body.toString())
            .put("redirect_uri", "postmessage");
        oauth2.authenticate(tokenConfig, ar -> {
            if (ar.succeeded() && ar.result() instanceof AccessToken) {
                final AccessToken accessToken = (AccessToken) ar.result();
                accessToken.setTrustJWT(true);
                final JsonObject user = accessToken.idToken();
                final String id = user.getString("sub");
                final String email = user.getString("email");
                final String hostedDomain = user.getString("hd");

                logger.info("Google User: id: " + id + " email: " + email + " domain: " + hostedDomain + " logged in");
                session.put("token", accessToken.opaqueAccessToken());
                session.put("id", id);
                session.put("email", email);
                session.put("domain", hostedDomain);
                response.setStatusCode(200);
                response.end("\"Successfully connected user.\"");
            } else {
                response.setStatusCode(500);
                response.end("\"Failed to read token data from Google. "
                    + ar.cause().getMessage() + "\"");
            }
        });
    });
}