io.vertx.ext.web.Session Java Examples

The following examples show how to use io.vertx.ext.web.Session. 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: RedisSessionStoreImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void get(String id, Handler<AsyncResult<Session>> resultHandler) {
  redis.send(cmd(GET).arg(id), resGet -> {
      if (resGet.failed()) {
        resultHandler.handle(Future.failedFuture(resGet.cause()));
        return;
      }

      Response response = resGet.result();
      if (response != null) {
        SharedDataSessionImpl session = new SharedDataSessionImpl(random);
        session.readFromBuffer(0, response.toBuffer());
        // postpone expiration time, this cannot be done in a single frame with GET cmd
        redis.send(cmd(PEXPIRE).arg(id).arg(session.timeout()), resExpire -> {
          if (resExpire.failed()) {
            resultHandler.handle(Future.failedFuture(resExpire.cause()));
          } else {
            resultHandler.handle(Future.succeededFuture(session));
          }
        });
      } else {
        resultHandler.handle(Future.succeededFuture());
      }
    });
}
 
Example #3
Source File: DigestAuthHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public String authenticateHeader(RoutingContext context) {
  final byte[] bytes = new byte[32];
  random.nextBytes(bytes);
  // generate nonce
  String nonce = md5(bytes);
  // save it
  nonces.put(nonce, new Nonce(0));

  // generate opaque
  String opaque = null;
  final Session session = context.session();
  if (session != null) {
    opaque = (String) session.data().get("opaque");
  }

  if (opaque == null) {
    random.nextBytes(bytes);
    // generate random opaque
    opaque = md5(bytes);
  }

  return "Digest realm=\"" + realm + "\", qop=\"auth\", nonce=\"" + nonce + "\", opaque=\"" + opaque + "\"";
}
 
Example #4
Source File: CSRFHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private String getTokenFromSession(RoutingContext ctx) {
  Session session = ctx.session();
  if (session == null) {
    return 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))) {
      return sessionToken.substring(idx + 1);
    }
  }
  // fail
  return null;
}
 
Example #5
Source File: ClusteredSessionStoreImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void get(String id, Handler<AsyncResult<Session>> resultHandler) {
  getMap(res -> {
    if (res.succeeded()) {
      res.result().get(id, res2 -> {
        if (res2.succeeded()) {
          AbstractSession session = (AbstractSession) res2.result();
          if (session != null) {
            session.setPRNG(random);
          }
          resultHandler.handle(Future.succeededFuture(res2.result()));
        } else {
          resultHandler.handle(Future.failedFuture(res2.cause()));
        }
      });
    } else {
      resultHandler.handle(Future.failedFuture(res.cause()));
    }
  });
}
 
Example #6
Source File: SessionHandlerTestBase.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testSessionFields() throws Exception {
	router.route().handler(SessionHandler.create(store));
	AtomicReference<String> rid = new AtomicReference<>();
	router.route().handler(rc -> {
		Session sess = rc.session();
		assertNotNull(sess);
		assertTrue(System.currentTimeMillis() - sess.lastAccessed() < 500);
		assertNotNull(sess.id());
		rid.set(sess.value());
		assertFalse(sess.isDestroyed());
		assertEquals(SessionHandler.DEFAULT_SESSION_TIMEOUT, sess.timeout());
		rc.response().end();
	});
	testRequest(HttpMethod.GET, "/", null, resp -> {
		String setCookie = resp.headers().get("set-cookie");
		assertTrue(setCookie.startsWith(SessionHandler.DEFAULT_SESSION_COOKIE_NAME + "="));
		int pos = setCookie.indexOf("; Path=" + SessionHandler.DEFAULT_SESSION_COOKIE_PATH);
		String sessID = setCookie.substring(18, pos);
		assertEquals(rid.get(), sessID);
	}, 200, "OK", null);
}
 
Example #7
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 #8
Source File: RedisSessionStoreImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void writeSession(Session session, Handler<AsyncResult<Void>> resultHandler) {
  Buffer buffer = Buffer.buffer();
  SharedDataSessionImpl sessionImpl = (SharedDataSessionImpl) session;
  sessionImpl.writeToBuffer(buffer);

  // submit with all session data & expiration TO in ms
  Request rq = cmd(SET)
    .arg(session.id()).arg(buffer)
    .arg("PX").arg(session.timeout());

  redis.send(rq, res -> {
    if (res.failed()) {
      resultHandler.handle(Future.failedFuture(res.cause()));
    } else {
      resultHandler.handle(Future.succeededFuture());
    }
  });
}
 
Example #9
Source File: MethodVisitor.java    From nubes with Apache License 2.0 6 votes vote down vote up
private void createParamsHandlers() {
  for (Parameter p : method.getParameters()) {
    Class<?> parameterClass = p.getType();
    if (Session.class.isAssignableFrom(parameterClass)) {
      usesSession = true;
    }
    Processor typeProcessor = config.getTypeProcessor(parameterClass);
    if (typeProcessor != null) {
      processors.add(typeProcessor);
    }
    Handler<RoutingContext> handler = config.getParamHandler(parameterClass);
    if (handler != null) {
      paramsHandlers.add(handler);
    }
    createParamAnnotationHandlers(p);
  }
}
 
Example #10
Source File: SessionHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void doGetSession(Vertx vertx, long startTime, String sessionID,
                          Handler<AsyncResult<Session>> resultHandler) {
    sessionStore.get(sessionID, res -> {
        if (res.succeeded()) {
            if (res.result() == null) {
                // Can't find it so retry. This is necessary for clustered sessions as it can
                // take sometime for the session
                // to propagate across the cluster so if the next request for the session comes
                // in quickly at a different
                // node there is a possibility it isn't available yet.
                long retryTimeout = sessionStore.retryTimeout();
                if (retryTimeout > 0 && System.currentTimeMillis() - startTime < retryTimeout) {
                    vertx.setTimer(5, v -> doGetSession(vertx, startTime, sessionID, resultHandler));
                    return;
                }
            }
        }
        resultHandler.handle(res);
    });
}
 
Example #11
Source File: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Test
public void storeShouldRemoveExpiredSessionFromLocalAndRemote(TestContext context) {
    Vertx vertx = rule.vertx();
    Async async = context.async();
    SessionStore sessionStore = NearCacheSessionStore.create(vertx);
    Session session = sessionStore.createSession(3000);
    sessionStore.put(session, context.asyncAssertSuccess());


    vertx.setTimer(5000, unused -> {
        sessionStore.get("XY", context.asyncAssertSuccess(u -> {
            doWithRemoteSession(context, session, context.asyncAssertSuccess(s ->
                context.assertNull(s, "Remote session should not be present")
            ));
            doWithLocalSession(context, session, context.asyncAssertSuccess(s ->
                context.assertNull(s, "Local session should not be present")
            ));
        }));
        async.complete();
    });
}
 
Example #12
Source File: SummerRouter.java    From Summer with MIT License 6 votes vote down vote up
private Object getContext(RoutingContext routingContext,ArgInfo argInfo){
    Class clz = argInfo.getClazz();
    if (clz ==RoutingContext.class){

        return routingContext;
    }else if (clz == HttpServerRequest.class){
        return routingContext.request();
    }else if (clz == HttpServerResponse.class){
        return routingContext.response();
    }else if (clz == Session.class){
        return routingContext.session();
    }else if (clz == Vertx.class){
        return vertx;
    }
    return null;
}
 
Example #13
Source File: RedisSessionStoreImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void put(Session session, Handler<AsyncResult<Void>> resultHandler) {
  redis.send(cmd(GET).arg(session.id()), res -> {
      if (res.failed()) {
        resultHandler.handle(Future.failedFuture(res.cause()));
        return;
      }

      AbstractSession newSession = (AbstractSession) session;
      Response response = res.result();
      if (response != null) {
        // Old session exists, we need to validate versions
        SharedDataSessionImpl oldSession = new SharedDataSessionImpl(random);
        oldSession.readFromBuffer(0, response.toBuffer());

        if (oldSession.version() != newSession.version()) {
          resultHandler.handle(Future.failedFuture("Session version mismatch"));
          return;
        }
      }

      newSession.incrementVersion();
      writeSession(newSession, resultHandler);
    });
}
 
Example #14
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 #15
Source File: VertxSessionStore.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean destroySession(final VertxWebContext context) {
    final Session vertxSession = getVertxSession(context);
    if (vertxSession != null) {
        vertxSession.destroy();
        return true;
    }
    return false;
}
 
Example #16
Source File: VertxSessionStore.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean renewSession(VertxWebContext context) {
    final Session vertxSession = getVertxSession(context);
    if (vertxSession != null) {
        vertxSession.regenerateId();
        return true;
    }
    return false;
}
 
Example #17
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 #18
Source File: InterceptableRoutingContextImplTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void testOthers() {
    Assert.assertEquals(mountPoint, contextToTest.mountPoint());
    Assert.assertEquals(Utils.normalizePath(mountPoint), contextToTest.normalisedPath());
    Assert.assertEquals(null, contextToTest.currentRoute());
    Assert.assertEquals(-1, contextToTest.statusCode());
    Assert.assertEquals(null, contextToTest.failure());
    Assert.assertEquals(myVertx, contextToTest.vertx());
    Assert.assertEquals(false, contextToTest.failed());

    Session sess = new SessionImpl();
    contextToTest.setSession(sess);
    Assert.assertEquals(sess, contextToTest.session());
}
 
Example #19
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 #20
Source File: VertxSessionStore.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Object> get(final VertxWebContext context, final String key) {
    final Session vertxSession = getVertxSession(context);
    if (vertxSession != null) {
        return Optional.ofNullable(vertxSession.get(key));
    }
    return Optional.empty();
}
 
Example #21
Source File: SessionHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
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);
    // only store the user if there's a auth provider
    addStoreSessionHandler(context, authProvider != null);
}
 
Example #22
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 #23
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 #24
Source File: CookielessSessionHandlerTestBase.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testLastAccessed2() throws Exception {
	router.route().handler(SessionHandler.create(store).setCookieless(true));
	AtomicReference<Session> rid = new AtomicReference<>();
	router.route().handler(rc -> {
		rid.set(rc.session());
		rc.session().put("foo", "bar");
		vertx.setTimer(1000, tid -> rc.response().end());
	});
	testRequest(HttpMethod.GET, "/", 200, "OK");
	// accessed() is called after request too
	assertTrue(rid.get().lastAccessed() - System.currentTimeMillis() < 500);
}
 
Example #25
Source File: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
public void storeShouldFireExpirationEvent(TestContext context) {
    Vertx vertx = rule.vertx();
    Async async = context.async(2);
    NearCacheSessionStore sessionStore = NearCacheSessionStore.create(vertx);
    sessionStore.expirationHandler(res -> async.countDown());

    Session session = sessionStore.createSession(1000);
    sessionStore.put(session, context.asyncAssertSuccess());

    Session session2 = sessionStore.createSession(3000);
    sessionStore.put(session2, context.asyncAssertSuccess());

}
 
Example #26
Source File: CookielessSessionHandlerTestBase.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue172_setnull() throws Exception {
	router.route().handler(SessionHandler.create(store).setCookieless(true));
	AtomicReference<Session> rid = new AtomicReference<>();

	router.route().handler(rc -> {
		rid.set(rc.session());
		rc.session().put("foo", null);
		vertx.setTimer(1000, tid -> rc.response().end());
	});
	testRequest(HttpMethod.GET, "/", 200, "OK");
}
 
Example #27
Source File: SessionHandlerTestBase.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testLastAccessed1() throws Exception {
   router.route().handler(SessionHandler.create(store));
   AtomicReference<Session> rid = new AtomicReference<>();
   router.route().handler(rc -> {
     rid.set(rc.session());
     rc.response().end();
   });
   testRequest(HttpMethod.GET, "/", 200, "OK");
   long start = rid.get().lastAccessed();
   int millis = 250;
   Thread.sleep(millis);
   testRequest(HttpMethod.GET, "/", 200, "OK");
   assertTrue(rid.get().lastAccessed() - start >= millis);
 }
 
Example #28
Source File: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Test
public void createSession(TestContext context) {

    Vertx vertx = rule.vertx();
    SessionStore sessionStore = NearCacheSessionStore.create(vertx);
    long beforeCreationTime = System.currentTimeMillis();
    Session session = sessionStore.createSession(3600);
    assertThat(session.id()).isNotEmpty();
    assertThat(session.timeout()).isEqualTo(3600);
    assertThat(session.lastAccessed()).isCloseTo(beforeCreationTime, Offset.offset(100L));
    assertThat(session.isDestroyed()).isFalse();

}
 
Example #29
Source File: NearCacheSessionStoreIT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void getRemoteMap(TestContext context, Handler<AsyncResult<AsyncMap<String, Session>>> resultHandler) {
    if (remoteMap == null) {
        rule.vertx().sharedData().<String, Session>getClusterWideMap(NearCacheSessionStore.DEFAULT_SESSION_MAP_NAME, res -> {
            if (res.succeeded()) {
                remoteMap = res.result();
                resultHandler.handle(Future.succeededFuture(res.result()));
            } else {
                resultHandler.handle(res);
            }
        });
    } else {
        resultHandler.handle(Future.succeededFuture(remoteMap));
    }
}
 
Example #30
Source File: RawWebSocketTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
RawWSSockJSSocket(Vertx vertx, Session webSession, User webUser, ServerWebSocket ws) {
  super(vertx, webSession, webUser);
  this.ws = ws;
  ws.closeHandler(v -> {
    // Make sure the writeHandler gets unregistered
    synchronized (RawWSSockJSSocket.this) {
      closed = true;
    }
    RawWSSockJSSocket.super.close();
  });
}