Java Code Examples for io.vertx.ext.web.Session#put()

The following examples show how to use io.vertx.ext.web.Session#put() . 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: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Test(timeout = 5000)
public void clearShouldEmptyLocalAndRemoteSession(TestContext context) {
    Vertx vertx = rule.vertx();
    SessionStore sessionStore = NearCacheSessionStore.create(vertx);
    Session session = sessionStore.createSession(DEFAULT_TIMEOUT);
    TestObject testObject = new TestObject("TestObject");
    session.put("TEST_KEY", testObject);

    sessionStore.clear(context.asyncAssertSuccess(u -> {
        context.assertTrue(localMap.isEmpty(), "Local map should be empty");
        remoteMap.size(context.asyncAssertSuccess(size ->
            context.assertTrue(size == 0, "Remote map should be empty")
        ));

    }));
}
 
Example 2
Source File: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Test(timeout = 5000)
public void clearShouldEmptyLocalAndRemoteSession(TestContext context) {
    Vertx vertx = rule.vertx();
    SessionStore sessionStore = NearCacheSessionStore.create(vertx);
    Session session = sessionStore.createSession(DEFAULT_TIMEOUT);
    TestObject testObject = new TestObject("TestObject");
    session.put("TEST_KEY", testObject);

    sessionStore.clear(context.asyncAssertSuccess(u -> {
        context.assertTrue(localMap.isEmpty(), "Local map should be empty");
        remoteMap.size(context.asyncAssertSuccess(size ->
            context.assertTrue(size == 0, "Remote map should be empty")
        ));

    }));
}
 
Example 3
Source File: RedirectAuthHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) {
    Session session = context.session();
    if (session != null) {
        try {
            // Save current request in session - we'll get redirected back here after successful login
            io.vertx.reactivex.core.http.HttpServerRequest request = new io.vertx.reactivex.core.http.HttpServerRequest(context.request());
            Map<String, String> requestParameters = request.params().entries().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

            session.put(returnURLParam, UriBuilderRequest.resolveProxyRequest(request, request.path(), requestParameters));

            // Now redirect to the login url
            String uri = UriBuilderRequest.resolveProxyRequest(request, loginRedirectURL, requestParameters, true);

            handler.handle(Future.failedFuture(new HttpStatusException(302, uri)));
        } catch (Exception e) {
            logger.warn("Failed to decode login redirect url", e);
            handler.handle(Future.failedFuture(new HttpStatusException(302, loginRedirectURL)));
        }
    } else {
        handler.handle(Future.failedFuture("No session - did you forget to include a SessionHandler?"));
    }
}
 
Example 4
Source File: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
public void deleteShouldRemoveSessionFromLocalAndRemote(TestContext context) {
    Vertx vertx = rule.vertx();
    SessionStore sessionStore = NearCacheSessionStore.create(vertx);
    Session session = sessionStore.createSession(DEFAULT_TIMEOUT);
    TestObject testObject = new TestObject("TestObject");
    session.put("TEST_KEY", testObject);

    sessionStore.delete("XY", context.asyncAssertSuccess(u -> {
        doWithLocalSession(context, session, context.asyncAssertSuccess(context::assertNull));
        doWithRemoteSession(context, session, context.asyncAssertSuccess(context::assertNull));
    }));
}
 
Example 5
Source File: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
public void deleteShouldRemoveSessionFromLocalAndRemote(TestContext context) {
    Vertx vertx = rule.vertx();
    SessionStore sessionStore = NearCacheSessionStore.create(vertx);
    Session session = sessionStore.createSession(DEFAULT_TIMEOUT);
    TestObject testObject = new TestObject("TestObject");
    session.put("TEST_KEY", testObject);

    sessionStore.delete("XY", context.asyncAssertSuccess(u -> {
        doWithLocalSession(context, session, context.asyncAssertSuccess(context::assertNull));
        doWithRemoteSession(context, session, context.asyncAssertSuccess(context::assertNull));
    }));
}
 
Example 6
Source File: VertxSessionStore.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public void set(final VertxWebContext context, final String key, final Object value) {
    final Session vertxSession = getVertxSession(context);
    if (vertxSession != null) {
        vertxSession.put(key, value);
    }
}
 
Example 7
Source File: RedirectAuthHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) {
  Session session = context.session();
  if (session != null) {
    // Now redirect to the login url - we'll get redirected back here after successful login
    session.put(returnURLParam, context.request().uri());
    handler.handle(Future.failedFuture(new HttpStatusException(302, loginRedirectURL)));
  } else {
    handler.handle(Future.failedFuture("No session - did you forget to include a SessionHandler?"));
  }
}
 
Example 8
Source File: ClusteredSessionHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void stuffSession(Session session) {
  session.put("somelong", 123456L);
  session.put("someint", 1234);
  session.put("someshort", (short) 123);
  session.put("somebyte", (byte) 12);
  session.put("somedouble", 123.456d);
  session.put("somefloat", 123.456f);
  session.put("somechar", 'X');
  session.put("somebooleantrue", true);
  session.put("somebooleanfalse", false);
  session.put("somestring", "wibble");
  session.put("somebytes", bytes);
  session.put("somebuffer", buffer);
  session.put("someclusterserializable", new JsonObject().put("foo", "bar"));
}
 
Example 9
Source File: CSRFHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {

  if (nagHttps) {
    String uri = ctx.request().absoluteURI();
    if (uri != null && !uri.startsWith("https:")) {
      log.trace("Using session cookies without https could make you susceptible to session hijacking: " + uri);
    }
  }

  HttpMethod method = ctx.request().method();
  Session session = ctx.session();

  // if we're being strict with the origin
  // ensure that they are always valid
  if (!isValidOrigin(ctx)) {
    ctx.fail(403);
    return;
  }

  switch (method.name()) {
    case "GET":
      final String token;

      if (session == null) {
        // if there's no session to store values, tokens are issued on every request
        token = generateAndStoreToken(ctx);
      } else {
        // get the token from the session, this also considers the fact
        // that the token might be invalid as it was issued for a previous session id
        // session id's change on session upgrades (unauthenticated -> authenticated; role change; etc...)
        String sessionToken = getTokenFromSession(ctx);
        // when there's no token in the session, then we behave just like when there is no session
        // create a new token, but we also store it in the session for the next runs
        if (sessionToken == null) {
          token = generateAndStoreToken(ctx);
          // storing will include the session id too. The reason is that if a session is upgraded
          // we don't want to allow the token to be valid anymore
          session.put(headerName, session.id() + "/" + token);
        } else {
          String[] parts = sessionToken.split("\\.");
          final long ts = parseLong(parts[1]);

          if (ts == -1) {
            // fallback as the token is expired
            token = generateAndStoreToken(ctx);
          } else {
            if (!(System.currentTimeMillis() > ts + timeout)) {
              // we're still on the same session, no need to regenerate the token
              // also note that the token isn't expired, so it can be reused
              token = sessionToken;
              // in this case specifically we don't issue the token as it is unchanged
              // the user agent still has it from the previous interaction.
            } else {
              // fallback as the token is expired
              token = generateAndStoreToken(ctx);
            }
          }
        }
      }
      // put the token in the context for users who prefer to render the token directly on the HTML
      ctx.put(headerName, token);
      ctx.next();
      break;
    case "POST":
    case "PUT":
    case "DELETE":
    case "PATCH":
      if (isValidRequest(ctx)) {
        // it matches, so refresh the token to avoid replay attacks
        token = generateAndStoreToken(ctx);
        // put the token in the context for users who prefer to
        // render the token directly on the HTML
        ctx.put(headerName, token);
        ctx.next();
      } else {
        ctx.fail(403);
      }
      break;
    default:
      // ignore other methods
      ctx.next();
      break;
  }
}