Search in sources :

Example 11 with SessionManager

use of io.undertow.server.session.SessionManager in project spring-boot by spring-projects.

the class UndertowServletWebServerFactory method createManager.

private DeploymentManager createManager(ServletContextInitializer... initializers) {
    DeploymentInfo deployment = Servlets.deployment();
    registerServletContainerInitializerToDriveServletContextInitializers(deployment, initializers);
    deployment.setClassLoader(getServletClassLoader());
    deployment.setContextPath(getContextPath());
    deployment.setDisplayName(getDisplayName());
    deployment.setDeploymentName("spring-boot");
    if (isRegisterDefaultServlet()) {
        deployment.addServlet(Servlets.servlet("default", DefaultServlet.class));
    }
    configureErrorPages(deployment);
    deployment.setServletStackTraces(ServletStackTraces.NONE);
    deployment.setResourceManager(getDocumentRootResourceManager());
    deployment.setTempDir(createTempDir("undertow"));
    deployment.setEagerFilterInit(this.eagerFilterInit);
    deployment.setPreservePathOnForward(this.preservePathOnForward);
    configureMimeMappings(deployment);
    configureWebListeners(deployment);
    for (UndertowDeploymentInfoCustomizer customizer : this.deploymentInfoCustomizers) {
        customizer.customize(deployment);
    }
    if (getSession().isPersistent()) {
        File dir = getValidSessionStoreDir();
        deployment.setSessionPersistenceManager(new FileSessionPersistence(dir));
    }
    addLocaleMappings(deployment);
    DeploymentManager manager = Servlets.newContainer().addDeployment(deployment);
    manager.deploy();
    if (manager.getDeployment() instanceof DeploymentImpl) {
        removeSuperfluousMimeMappings((DeploymentImpl) manager.getDeployment(), deployment);
    }
    SessionManager sessionManager = manager.getDeployment().getSessionManager();
    Duration timeoutDuration = getSession().getTimeout();
    int sessionTimeout = (isZeroOrLess(timeoutDuration) ? -1 : (int) timeoutDuration.getSeconds());
    sessionManager.setDefaultSessionTimeout(sessionTimeout);
    return manager;
}
Also used : DeploymentManager(io.undertow.servlet.api.DeploymentManager) SessionManager(io.undertow.server.session.SessionManager) DeploymentImpl(io.undertow.servlet.core.DeploymentImpl) Duration(java.time.Duration) DefaultServlet(io.undertow.servlet.handlers.DefaultServlet) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) File(java.io.File)

Example 12 with SessionManager

use of io.undertow.server.session.SessionManager in project undertow by undertow-io.

the class ServletFormAuthenticationMechanism method storeInitialLocation.

@Override
protected void storeInitialLocation(final HttpServerExchange exchange) {
    if (!saveOriginalRequest) {
        return;
    }
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
    Session session;
    if (System.getSecurityManager() == null) {
        session = httpSession.getSession();
    } else {
        session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
    }
    SessionManager manager = session.getSessionManager();
    if (seenSessionManagers.add(manager)) {
        manager.registerSessionListener(LISTENER);
    }
    session.setAttribute(SESSION_KEY, RedirectBuilder.redirect(exchange, exchange.getRelativePath()));
    SavedRequest.trySaveRequest(exchange);
}
Also used : HttpSessionImpl(io.undertow.servlet.spec.HttpSessionImpl) SessionManager(io.undertow.server.session.SessionManager) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) Session(io.undertow.server.session.Session)

Example 13 with SessionManager

use of io.undertow.server.session.SessionManager in project wildfly by wildfly.

the class DistributableSingleSignOnTestCase method remove.

@Test
public void remove() {
    String deployment = "deployment";
    BatchContext context = mock(BatchContext.class);
    Session session = mock(Session.class);
    SessionManager manager = mock(SessionManager.class);
    Sessions<String, String> sessions = mock(Sessions.class);
    when(this.batcher.resumeBatch(this.batch)).thenReturn(context);
    when(session.getSessionManager()).thenReturn(manager);
    when(manager.getDeploymentName()).thenReturn(deployment);
    when(this.sso.getSessions()).thenReturn(sessions);
    this.subject.remove(session);
    verify(sessions).removeSession(deployment);
    verifyZeroInteractions(this.batch);
    verify(context).close();
}
Also used : SessionManager(io.undertow.server.session.SessionManager) BatchContext(org.wildfly.clustering.ee.BatchContext) Session(io.undertow.server.session.Session) AuthenticatedSession(io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession) Test(org.junit.Test)

Example 14 with SessionManager

use of io.undertow.server.session.SessionManager in project wildfly by wildfly.

the class DistributableSingleSignOnTestCase method iterator.

@Test
public void iterator() {
    BatchContext context = mock(BatchContext.class);
    Sessions<String, String> sessions = mock(Sessions.class);
    SessionManager manager = mock(SessionManager.class);
    Session session = mock(Session.class);
    String deployment = "deployment";
    String sessionId = "session";
    when(this.batcher.resumeBatch(this.batch)).thenReturn(context);
    when(this.sso.getSessions()).thenReturn(sessions);
    when(sessions.getDeployments()).thenReturn(Collections.singleton(deployment));
    when(sessions.getSession(deployment)).thenReturn(sessionId);
    when(this.registry.getSessionManager(deployment)).thenReturn(manager);
    when(manager.getSession(sessionId)).thenReturn(session);
    when(session.getId()).thenReturn(sessionId);
    Iterator<Session> results = this.subject.iterator();
    assertTrue(results.hasNext());
    Session result = results.next();
    assertEquals(session.getId(), result.getId());
    assertFalse(results.hasNext());
    verifyZeroInteractions(this.batch);
    verify(context).close();
    // Validate that returned sessions can be invalidated
    HttpServerExchange exchange = new HttpServerExchange(null);
    Session mutableSession = mock(Session.class);
    when(session.getSessionManager()).thenReturn(manager);
    when(manager.getSession(same(exchange), Matchers.<SessionConfig>any())).thenReturn(mutableSession);
    result.invalidate(exchange);
    verify(mutableSession).invalidate(same(exchange));
    verifyZeroInteractions(this.batch);
    verifyNoMoreInteractions(context);
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) SessionManager(io.undertow.server.session.SessionManager) BatchContext(org.wildfly.clustering.ee.BatchContext) Session(io.undertow.server.session.Session) AuthenticatedSession(io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession) Test(org.junit.Test)

Example 15 with SessionManager

use of io.undertow.server.session.SessionManager in project undertow by undertow-io.

the class SessionServer method main.

public static void main(String[] args) {
    PathHandler pathHandler = new PathHandler();
    pathHandler.addPrefixPath("/", new HttpHandler() {

        public void handleRequest(HttpServerExchange exchange) throws Exception {
            StringBuilder sb = new StringBuilder();
            sb.append("<form action='addToSession' >");
            sb.append("<label>Attribute Name</label>");
            sb.append("<input name='attrName' />");
            sb.append("<label>Attribute Value</label>");
            sb.append("<input name='value' />");
            sb.append("<button>Save to Session</button>");
            // To retrive the SessionManager use the attachmentKey
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            // same goes to SessionConfig
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            sb.append("</form>");
            sb.append("<a href='/destroySession'>Destroy Session</a>");
            sb.append("<br/>");
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            sb.append("<ul>");
            for (String string : session.getAttributeNames()) {
                sb.append("<li>" + string + " : " + session.getAttribute(string) + "</li>");
            }
            sb.append("</ul>");
            exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/html;");
            exchange.getResponseSender().send(sb.toString());
        }
    });
    pathHandler.addPrefixPath("/addToSession", new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            Map<String, Deque<String>> reqParams = exchange.getQueryParameters();
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            Deque<String> deque = reqParams.get("attrName");
            Deque<String> dequeVal = reqParams.get("value");
            session.setAttribute(deque.getLast(), dequeVal.getLast());
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
            exchange.getResponseHeaders().put(Headers.LOCATION, "/");
            exchange.getResponseSender().close();
        }
    });
    pathHandler.addPrefixPath("/destroySession", new HttpHandler() {

        public void handleRequest(HttpServerExchange exchange) throws Exception {
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            session.invalidate(exchange);
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
            exchange.getResponseHeaders().put(Headers.LOCATION, "/");
            exchange.getResponseSender().close();
        }
    });
    SessionManager sessionManager = new InMemorySessionManager("SESSION_MANAGER");
    SessionCookieConfig sessionConfig = new SessionCookieConfig();
    /*
         * Use the sessionAttachmentHandler to add the sessionManager and
         * sessionCofing to the exchange of every request
         */
    SessionAttachmentHandler sessionAttachmentHandler = new SessionAttachmentHandler(sessionManager, sessionConfig);
    // set as next handler your root handler
    sessionAttachmentHandler.setNext(pathHandler);
    System.out.println("Open the url and fill the form to add attributes into the session");
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(sessionAttachmentHandler).build();
    server.start();
}
Also used : HttpHandler(io.undertow.server.HttpHandler) SessionManager(io.undertow.server.session.SessionManager) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) PathHandler(io.undertow.server.handlers.PathHandler) SessionConfig(io.undertow.server.session.SessionConfig) Deque(java.util.Deque) HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) Map(java.util.Map) Undertow(io.undertow.Undertow) Session(io.undertow.server.session.Session) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager)

Aggregations

SessionManager (io.undertow.server.session.SessionManager)23 Session (io.undertow.server.session.Session)19 Test (org.junit.Test)9 HttpServerExchange (io.undertow.server.HttpServerExchange)8 AuthenticatedSession (io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession)7 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)7 HttpHandler (io.undertow.server.HttpHandler)6 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)6 SessionConfig (io.undertow.server.session.SessionConfig)6 BatchContext (org.wildfly.clustering.ee.BatchContext)6 HttpString (io.undertow.util.HttpString)5 IOException (java.io.IOException)5 SessionCookieConfig (io.undertow.server.session.SessionCookieConfig)4 DeploymentManager (io.undertow.servlet.api.DeploymentManager)4 TestHttpClient (io.undertow.testutils.TestHttpClient)4 Header (org.apache.http.Header)4 HttpResponse (org.apache.http.HttpResponse)4 HttpGet (org.apache.http.client.methods.HttpGet)4 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)3 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)3