Search in sources :

Example 26 with Session

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

the class ServletContextImpl method getSession.

public HttpSessionImpl getSession(final ServletContextImpl originalServletContext, final HttpServerExchange exchange, boolean create) {
    SessionConfig c = originalServletContext.getSessionConfig();
    HttpSessionImpl httpSession = exchange.getAttachment(sessionAttachmentKey);
    if (httpSession != null && httpSession.isInvalid()) {
        exchange.removeAttachment(sessionAttachmentKey);
        httpSession = null;
    }
    if (httpSession == null) {
        final SessionManager sessionManager = deployment.getSessionManager();
        Session session = sessionManager.getSession(exchange, c);
        if (session != null) {
            httpSession = SecurityActions.forSession(session, this, false);
            exchange.putAttachment(sessionAttachmentKey, httpSession);
        } else if (create) {
            String existing = c.findSessionId(exchange);
            Boolean isRequestedSessionIdSaved = exchange.getAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID_SET);
            if (isRequestedSessionIdSaved == null || !isRequestedSessionIdSaved) {
                exchange.putAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID_SET, Boolean.TRUE);
                exchange.putAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID, existing);
            }
            if (originalServletContext != this) {
                // this is a cross context request
                // we need to make sure there is a top level session
                final HttpSessionImpl topLevel = originalServletContext.getSession(originalServletContext, exchange, true);
                // override the session id to just return the same ID as the top level session
                c = new SessionConfig() {

                    @Override
                    public void setSessionId(HttpServerExchange exchange, String sessionId) {
                    // noop
                    }

                    @Override
                    public void clearSession(HttpServerExchange exchange, String sessionId) {
                    // noop
                    }

                    @Override
                    public String findSessionId(HttpServerExchange exchange) {
                        return topLevel.getId();
                    }

                    @Override
                    public SessionCookieSource sessionCookieSource(HttpServerExchange exchange) {
                        return SessionCookieSource.NONE;
                    }

                    @Override
                    public String rewriteUrl(String originalUrl, String sessionId) {
                        return null;
                    }
                };
                // first we check if there is a session with this id already
                // this can happen with a shared session manager
                session = sessionManager.getSession(exchange, c);
                if (session != null) {
                    httpSession = SecurityActions.forSession(session, this, false);
                    exchange.putAttachment(sessionAttachmentKey, httpSession);
                }
            } else if (existing != null) {
                if (getDeploymentInfo().isCheckOtherSessionManagers()) {
                    boolean found = false;
                    for (String deploymentName : deployment.getServletContainer().listDeployments()) {
                        DeploymentManager deployment = this.deployment.getServletContainer().getDeployment(deploymentName);
                        if (deployment != null) {
                            if (deployment.getDeployment().getSessionManager().getSession(existing) != null) {
                                found = true;
                                break;
                            }
                        }
                    }
                    if (!found) {
                        c.clearSession(exchange, existing);
                    }
                } else {
                    c.clearSession(exchange, existing);
                }
            }
            if (httpSession == null) {
                final Session newSession = sessionManager.createSession(exchange, c);
                httpSession = SecurityActions.forSession(newSession, this, true);
                exchange.putAttachment(sessionAttachmentKey, httpSession);
            }
        }
    }
    return httpSession;
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) DeploymentManager(io.undertow.servlet.api.DeploymentManager) SessionManager(io.undertow.server.session.SessionManager) SslSessionConfig(io.undertow.server.session.SslSessionConfig) PathParameterSessionConfig(io.undertow.server.session.PathParameterSessionConfig) SessionConfig(io.undertow.server.session.SessionConfig) Session(io.undertow.server.session.Session)

Example 27 with Session

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

the class SSLSessionTestCase method testSslSession.

@Test
public void testSslSession() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {
        InMemorySessionManager sessionManager = new InMemorySessionManager("");
        final SslSessionConfig sessionConfig = new SslSessionConfig(sessionManager);
        final SessionAttachmentHandler handler = new SessionAttachmentHandler(sessionManager, sessionConfig).setNext(new HttpHandler() {

            @Override
            public void handleRequest(final HttpServerExchange exchange) throws Exception {
                final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
                Session session = manager.getSession(exchange, sessionConfig);
                if (session == null) {
                    session = manager.createSession(exchange, sessionConfig);
                    session.setAttribute(COUNT, 0);
                }
                Integer count = (Integer) session.getAttribute(COUNT);
                exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
                session.setAttribute(COUNT, ++count);
            }
        });
        DefaultServer.startSSLServer();
        client.setSSLContext(DefaultServer.getClientSSLContext());
        DefaultServer.setRootHandler(handler);
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        Header[] header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("1", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("2", header[0].getValue());
        Assert.assertEquals(0, client.getCookieStore().getCookies().size());
    } finally {
        DefaultServer.stopSSLServer();
        client.getConnectionManager().shutdown();
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) SessionManager(io.undertow.server.session.SessionManager) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) TestHttpClient(io.undertow.testutils.TestHttpClient) HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) SslSessionConfig(io.undertow.server.session.SslSessionConfig) Header(org.apache.http.Header) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) Session(io.undertow.server.session.Session) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Example 28 with Session

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

the class ServletFormAuthenticationMechanism method storeInitialLocation.

/**
 * This method doesn't save content of request but instead uses data from parameter.
 * This should be used in case that data from request was already read and therefore it is not possible to save them.
 *
 * @param exchange
 * @param bytes
 * @param contentLength
 */
protected void storeInitialLocation(final HttpServerExchange exchange, byte[] bytes, int contentLength) {
    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()));
    if (bytes == null) {
        SavedRequest.trySaveRequest(exchange);
    } else {
        SavedRequest.trySaveRequest(exchange, bytes, contentLength);
    }
}
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 29 with Session

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

the class SessionListenerBridge method sessionDestroyed.

@Override
public void sessionDestroyed(final Session session, final HttpServerExchange exchange, final SessionDestroyedReason reason) {
    if (reason == SessionDestroyedReason.TIMEOUT) {
        try {
            // we need to perform thread setup actions
            destroyedAction.call(exchange, session);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        doDestroy(session);
    }
    ServletRequestContext current = SecurityActions.currentServletRequestContext();
    Session underlying = null;
    if (current != null && current.getSession() != null) {
        if (System.getSecurityManager() == null) {
            underlying = current.getSession().getSession();
        } else {
            underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(current.getSession()));
        }
    }
    if (current != null && underlying == session) {
        current.setSession(null);
    }
}
Also used : ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) ServletException(javax.servlet.ServletException) Session(io.undertow.server.session.Session)

Example 30 with Session

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

the class JsrWebSocketFilter method doFilter.

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    if (req.getHeader(Headers.UPGRADE_STRING) != null) {
        final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(req, resp, peerConnections);
        String path;
        if (req.getPathInfo() == null) {
            path = req.getServletPath();
        } else {
            path = req.getServletPath() + req.getPathInfo();
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        PathTemplateMatcher.PathMatchResult<WebSocketHandshakeHolder> matchResult = pathTemplateMatcher.match(path);
        if (matchResult != null) {
            Handshake handshaker = null;
            for (Handshake method : matchResult.getValue().handshakes) {
                if (method.matches(facade)) {
                    handshaker = method;
                    break;
                }
            }
            if (handshaker != null) {
                if (container.isClosed()) {
                    resp.sendError(StatusCodes.SERVICE_UNAVAILABLE);
                    return;
                }
                facade.putAttachment(HandshakeUtil.PATH_PARAMS, matchResult.getParameters());
                facade.putAttachment(HandshakeUtil.PRINCIPAL, req.getUserPrincipal());
                final Handshake selected = handshaker;
                ServletRequestContext src = ServletRequestContext.requireCurrent();
                final HttpSessionImpl session = src.getCurrentServletContext().getSession(src.getExchange(), false);
                facade.upgradeChannel(new HttpUpgradeListener() {

                    @Override
                    public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
                        WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
                        peerConnections.add(channel);
                        if (session != null) {
                            final Session underlying;
                            if (System.getSecurityManager() == null) {
                                underlying = session.getSession();
                            } else {
                                underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
                            }
                            List<WebSocketChannel> connections;
                            synchronized (underlying) {
                                connections = (List<WebSocketChannel>) underlying.getAttribute(SESSION_ATTRIBUTE);
                                if (connections == null) {
                                    underlying.setAttribute(SESSION_ATTRIBUTE, connections = new ArrayList<>());
                                }
                                connections.add(channel);
                            }
                            final List<WebSocketChannel> finalConnections = connections;
                            channel.addCloseTask(new ChannelListener<WebSocketChannel>() {

                                @Override
                                public void handleEvent(WebSocketChannel channel) {
                                    synchronized (underlying) {
                                        finalConnections.remove(channel);
                                    }
                                }
                            });
                        }
                        callback.onConnect(facade, channel);
                    }
                });
                handshaker.handshake(facade);
                return;
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : ChannelListener(org.xnio.ChannelListener) WebSocketHandshakeHolder(io.undertow.websockets.jsr.ServerWebSocketContainer.WebSocketHandshakeHolder) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) StreamConnection(org.xnio.StreamConnection) ServletWebSocketHttpExchange(io.undertow.servlet.websockets.ServletWebSocketHttpExchange) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServerExchange(io.undertow.server.HttpServerExchange) PathTemplateMatcher(io.undertow.util.PathTemplateMatcher) HttpSessionImpl(io.undertow.servlet.spec.HttpSessionImpl) ArrayList(java.util.ArrayList) List(java.util.List) HttpUpgradeListener(io.undertow.server.HttpUpgradeListener) Handshake(io.undertow.websockets.core.protocol.Handshake) Session(io.undertow.server.session.Session)

Aggregations

Session (io.undertow.server.session.Session)33 SessionManager (io.undertow.server.session.SessionManager)19 Test (org.junit.Test)10 HttpServerExchange (io.undertow.server.HttpServerExchange)9 AuthenticatedSession (io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession)7 ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)7 HttpSessionImpl (io.undertow.servlet.spec.HttpSessionImpl)7 HttpString (io.undertow.util.HttpString)7 HttpHandler (io.undertow.server.HttpHandler)6 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)6 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)6 IOException (java.io.IOException)6 BatchContext (org.wildfly.clustering.ee.BatchContext)6 SessionConfig (io.undertow.server.session.SessionConfig)5 SessionCookieConfig (io.undertow.server.session.SessionCookieConfig)4 TestHttpClient (io.undertow.testutils.TestHttpClient)4 Map (java.util.Map)4 Header (org.apache.http.Header)4 HttpResponse (org.apache.http.HttpResponse)4 HeaderMap (io.undertow.util.HeaderMap)3