Search in sources :

Example 51 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class ServletSingleSignOnAuthenticationMechanism method getSession.

@Override
protected Session getSession(HttpServerExchange exchange) {
    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    final HttpSessionImpl session = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
    if (System.getSecurityManager() == null) {
        return session.getSession();
    } else {
        return AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
    }
}
Also used : HttpSessionImpl(io.undertow.servlet.spec.HttpSessionImpl) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Example 52 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class EndpointSessionHandler method onConnect.

@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    ConfiguredServerEndpoint config = HandshakeUtil.getConfig(channel);
    try {
        if (container.isClosed()) {
            // if the underlying container is closed we just reject
            channel.sendClose();
            channel.resumeReceives();
            return;
        }
        InstanceFactory<?> endpointFactory = config.getEndpointFactory();
        ServerEndpointConfig.Configurator configurator = config.getEndpointConfiguration().getConfigurator();
        final InstanceHandle<?> instance;
        DefaultContainerConfigurator.setCurrentInstanceFactory(endpointFactory);
        final Object instanceFromConfigurator = configurator.getEndpointInstance(config.getEndpointConfiguration().getEndpointClass());
        final InstanceHandle<?> factoryInstance = DefaultContainerConfigurator.clearCurrentInstanceFactory();
        if (factoryInstance == null) {
            instance = new ImmediateInstanceHandle<>(instanceFromConfigurator);
        } else if (factoryInstance.getInstance() == instanceFromConfigurator) {
            instance = factoryInstance;
        } else {
            // the default instance has been wrapped
            instance = new InstanceHandle<Object>() {

                @Override
                public Object getInstance() {
                    return instanceFromConfigurator;
                }

                @Override
                public void release() {
                    factoryInstance.release();
                }
            };
        }
        ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        Principal principal = exchange.getAttachment(HandshakeUtil.PRINCIPAL);
        if (principal == null) {
            if (src.getServletRequest() instanceof HttpServletRequest) {
                principal = ((HttpServletRequest) src.getServletRequest()).getUserPrincipal();
            } else {
                principal = src.getOriginalRequest().getUserPrincipal();
            }
        }
        final InstanceHandle<Endpoint> endpointInstance;
        if (config.getAnnotatedEndpointFactory() != null) {
            final AnnotatedEndpoint annotated = config.getAnnotatedEndpointFactory().createInstance(instance);
            endpointInstance = new InstanceHandle<Endpoint>() {

                @Override
                public Endpoint getInstance() {
                    return annotated;
                }

                @Override
                public void release() {
                    instance.release();
                }
            };
        } else {
            endpointInstance = (InstanceHandle<Endpoint>) instance;
        }
        final String scheme = channel.getRequestScheme() + "://";
        final String host = exchange.getRequestHeader(Headers.HOST_STRING);
        final String path = exchange.getRequestURI();
        UndertowSession session = new UndertowSession(channel, URI.create(scheme + host + path), exchange.getAttachment(HandshakeUtil.PATH_PARAMS), exchange.getRequestParameters(), this, principal, endpointInstance, config.getEndpointConfiguration(), exchange.getQueryString(), config.getEncodingFactory().createEncoding(config.getEndpointConfiguration()), config, channel.getSubProtocol(), Collections.<Extension>emptyList(), null);
        config.addOpenSession(session);
        session.setMaxBinaryMessageBufferSize(getContainer().getDefaultMaxBinaryMessageBufferSize());
        session.setMaxTextMessageBufferSize(getContainer().getDefaultMaxTextMessageBufferSize());
        session.setMaxIdleTimeout(getContainer().getDefaultMaxSessionIdleTimeout());
        session.getAsyncRemote().setSendTimeout(getContainer().getDefaultAsyncSendTimeout());
        try {
            endpointInstance.getInstance().onOpen(session, config.getEndpointConfiguration());
        } catch (Exception e) {
            endpointInstance.getInstance().onError(session, e);
            IoUtils.safeClose(session);
        }
        channel.resumeReceives();
    } catch (Exception e) {
        JsrWebSocketLogger.REQUEST_LOGGER.endpointCreationFailed(e);
        IoUtils.safeClose(channel);
    }
}
Also used : ServerEndpointConfig(jakarta.websocket.server.ServerEndpointConfig) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) Endpoint(jakarta.websocket.Endpoint) InstanceHandle(io.undertow.servlet.api.InstanceHandle) ImmediateInstanceHandle(io.undertow.servlet.util.ImmediateInstanceHandle) Principal(java.security.Principal)

Example 53 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext 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) {
                        HandshakeUtil.propagate(exchange, facade);
                        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(jakarta.servlet.http.HttpServletResponse) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) StreamConnection(org.xnio.StreamConnection) ServletWebSocketHttpExchange(io.undertow.servlet.websockets.ServletWebSocketHttpExchange) HttpServletRequest(jakarta.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)

Example 54 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class ServletAuthenticationCallHandler method handleRequest.

/**
 * Only allow the request through if successfully authenticated or if authentication is not required.
 *
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }
    SecurityContext context = exchange.getSecurityContext();
    if (context.authenticate()) {
        if (!exchange.isComplete()) {
            next.handleRequest(exchange);
        }
    } else {
        if (exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
            ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
            src.getOriginalResponse().sendError(exchange.getStatusCode());
        } else {
            exchange.endExchange();
        }
    }
}
Also used : SecurityContext(io.undertow.security.api.SecurityContext) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Example 55 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class ServletBlockingHttpExchange method close.

@Override
public void close() throws IOException {
    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (!exchange.isComplete()) {
        try {
            HttpServletRequestImpl request = servletRequestContext.getOriginalRequest();
            request.closeAndDrainRequest();
        } finally {
            HttpServletResponseImpl response = servletRequestContext.getOriginalResponse();
            response.closeStreamAndWriter();
        }
    } else {
        try {
            HttpServletRequestImpl request = servletRequestContext.getOriginalRequest();
            request.freeResources();
        } finally {
            HttpServletResponseImpl response = servletRequestContext.getOriginalResponse();
            response.freeResources();
        }
    }
}
Also used : HttpServletRequestImpl(io.undertow.servlet.spec.HttpServletRequestImpl) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) HttpServletResponseImpl(io.undertow.servlet.spec.HttpServletResponseImpl)

Aggregations

ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)71 IOException (java.io.IOException)13 HttpServerExchange (io.undertow.server.HttpServerExchange)12 HttpSessionImpl (io.undertow.servlet.spec.HttpSessionImpl)11 Session (io.undertow.server.session.Session)10 HttpServletRequestImpl (io.undertow.servlet.spec.HttpServletRequestImpl)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 ServletException (jakarta.servlet.ServletException)6 ServletRequest (javax.servlet.ServletRequest)6 Account (io.undertow.security.idm.Account)5 HttpServletResponseImpl (io.undertow.servlet.spec.HttpServletResponseImpl)5 HttpString (io.undertow.util.HttpString)5 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)5 SecurityContext (io.undertow.security.api.SecurityContext)4 HttpHandler (io.undertow.server.HttpHandler)3 SessionManager (io.undertow.server.session.SessionManager)3 ServletInfo (io.undertow.servlet.api.ServletInfo)3 ArrayList (java.util.ArrayList)3 HttpSession (javax.servlet.http.HttpSession)3 GenericMessageInfo (org.jboss.security.auth.message.GenericMessageInfo)3