Search in sources :

Example 66 with ServletRequestContext

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

the class ServletSamlAuthMech method servePage.

@Override
protected Integer servePage(HttpServerExchange exchange, String location) {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletRequest req = servletRequestContext.getServletRequest();
    ServletResponse resp = servletRequestContext.getServletResponse();
    RequestDispatcher disp = req.getRequestDispatcher(location);
    // make sure the login page is never cached
    exchange.getResponseHeaders().add(Headers.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
    exchange.getResponseHeaders().add(Headers.PRAGMA, "no-cache");
    exchange.getResponseHeaders().add(Headers.EXPIRES, "0");
    try {
        disp.forward(req, resp);
    } catch (ServletException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}
Also used : ServletException(javax.servlet.ServletException) ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) IOException(java.io.IOException) RequestDispatcher(javax.servlet.RequestDispatcher)

Example 67 with ServletRequestContext

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

the class ServletSamlSessionStore method saveAccount.

@Override
public void saveAccount(SamlSession account) {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpSession session = getSession(true);
    session.setAttribute(SamlSession.class.getName(), account);
    sessionManagement.login(servletRequestContext.getDeployment().getSessionManager());
    String sessionId = changeSessionId(session);
    idMapperUpdater.map(idMapper, account.getSessionIndex(), account.getPrincipal().getSamlSubject(), sessionId);
}
Also used : HttpSession(javax.servlet.http.HttpSession) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) SamlSession(org.keycloak.adapters.saml.SamlSession)

Example 68 with ServletRequestContext

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

the class ServletSamlSessionStore method getRedirectUri.

@Override
public String getRedirectUri() {
    final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
    String redirect = (String) session.getAttribute(SAML_REDIRECT_URI);
    if (redirect == null) {
        ServletHttpFacade facade = new ServletHttpFacade(exchange);
        HttpServletRequest req = (HttpServletRequest) sc.getServletRequest();
        String contextPath = req.getContextPath();
        String baseUri = KeycloakUriBuilder.fromUri(req.getRequestURL().toString()).replacePath(contextPath).build().toString();
        return SamlUtil.getRedirectTo(facade, contextPath, baseUri);
    }
    return redirect;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSessionImpl(io.undertow.servlet.spec.HttpSessionImpl) ServletHttpFacade(org.keycloak.adapters.undertow.ServletHttpFacade) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Example 69 with ServletRequestContext

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

the class WildflyServletRequestListener method getWildflyResponse.

private WildflyResponse getWildflyResponse(HttpServletRequest httpServletRequest) {
    if (httpServletRequest instanceof HttpServletRequestImpl) {
        HttpServerExchange exchange = ((HttpServletRequestImpl) httpServletRequest).getExchange();
        ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        if (servletRequestContext != null) {
            ServletResponse response = servletRequestContext.getServletResponse();
            if (response instanceof HttpServletResponseImpl) {
                return new WildflyResponse((HttpServletResponseImpl) response);
            }
        }
    }
    return null;
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) ServletResponse(javax.servlet.ServletResponse) HttpServletRequestImpl(io.undertow.servlet.spec.HttpServletRequestImpl) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) HttpServletResponseImpl(io.undertow.servlet.spec.HttpServletResponseImpl)

Example 70 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project org.ops4j.pax.web by ops4j.

the class Context method doCreateHandler.

private void doCreateHandler(Consumer<ServletContext> consumer) throws ServletException {
    LOG.debug("Creating handler for context /{}", contextModel.getContextName());
    final WebContainerContext httpContext = contextModel.getHttpContext();
    DeploymentInfo deployment = new DeploymentInfo();
    deployment.setEagerFilterInit(true);
    deployment.setDeploymentName(contextModel.getContextName());
    deployment.setDisplayName(httpContext.getContextId());
    deployment.setContextPath('/' + contextModel.getContextName());
    deployment.setClassLoader(classLoader);
    BundleContext bundleContext = contextModel.getBundle().getBundleContext();
    if (bundleContext != null) {
        deployment.addServletContextAttribute(WebContainerConstants.BUNDLE_CONTEXT_ATTRIBUTE, bundleContext);
        deployment.addServletContextAttribute("org.springframework.osgi.web.org.osgi.framework.BundleContext", bundleContext);
    }
    deployment.setResourceManager(this);
    // TODO: move to XML configuration
    deployment.setIdentityManager(identityManager);
    if (contextModel.getRealmName() != null && contextModel.getAuthMethod() != null) {
        ServletExtension authenticator = getAuthenticator(contextModel.getAuthMethod());
        if (authenticator != null) {
            deployment.getServletExtensions().add(authenticator);
        }
        LoginConfig cfg = new LoginConfig(contextModel.getAuthMethod(), contextModel.getRealmName(), contextModel.getFormLoginPage(), contextModel.getFormErrorPage());
        deployment.setLoginConfig(cfg);
    }
    boolean defaultServletAdded = false;
    ServletModel fallbackDefaultServlet = null;
    for (ServletModel servlet : servlets) {
        if (servlet instanceof ResourceModel && "default".equalsIgnoreCase(servlet.getName())) {
            // this is a default resource, so ignore it
            fallbackDefaultServlet = servlet;
            // we have to configure webapp-wide welcome files here
            List<String> welcomePages = new LinkedList<>();
            welcomeFiles.forEach(model -> welcomePages.addAll(Arrays.asList(model.getWelcomeFiles())));
            if (welcomePages.size() > 0) {
                ((ResourceServlet) servlet.getServlet()).configureWelcomeFiles(welcomePages);
            }
            continue;
        }
        ServletInfo info = new ServletInfo(servlet.getName(), clazz(servlet.getServletClass(), servlet.getServlet()), factory(servlet.getServletClass(), servlet.getServlet()));
        for (Map.Entry<String, String> param : servlet.getInitParams().entrySet()) {
            info.addInitParam(param.getKey(), param.getValue());
        }
        info.addMappings(servlet.getUrlPatterns());
        defaultServletAdded = servlet.getUrlPatterns() != null && Arrays.stream(servlet.getUrlPatterns()).anyMatch("/"::equals);
        if (Boolean.valueOf(servlet.getInitParams().get("async-supported"))) {
            info.setAsyncSupported(true);
        } else {
            info.setAsyncSupported(servlet.getAsyncSupported() != null ? servlet.getAsyncSupported() : false);
        }
        info.setLoadOnStartup(servlet.getLoadOnStartup() != null ? servlet.getLoadOnStartup() : -1);
        deployment.addServlet(info);
    }
    if (!defaultServletAdded && fallbackDefaultServlet != null) {
        LOG.info("Adding implicit \"default\" servlet");
        ServletInfo info = new ServletInfo(fallbackDefaultServlet.getName(), clazz(fallbackDefaultServlet.getServletClass(), fallbackDefaultServlet.getServlet()), factory(fallbackDefaultServlet.getServletClass(), fallbackDefaultServlet.getServlet()));
        info.setLoadOnStartup(0);
        doStart(fallbackDefaultServlet);
        deployment.addServlet(info);
    }
    for (WelcomeFileModel welcomeFile : welcomeFiles) {
        deployment.addWelcomePages(welcomeFile.getWelcomeFiles());
    }
    for (ErrorPageModel errorPage : errorPages) {
        try {
            int error = Integer.parseInt(errorPage.getError());
            deployment.addErrorPage(new ErrorPage(errorPage.getLocation(), error));
        } catch (NumberFormatException nfe) {
            // in the end - it's just a io.undertow.servlet.core.ErrorPages.errorCodeLocations map of code -> location
            if ("4xx".equals(errorPage.getError())) {
                for (int c = 400; c < 500; c++) {
                    deployment.addErrorPage(new ErrorPage(errorPage.getLocation(), c));
                }
            } else if ("5xx".equals(errorPage.getError())) {
                for (int c = 500; c < 600; c++) {
                    deployment.addErrorPage(new ErrorPage(errorPage.getLocation(), c));
                }
            } else {
                // must be an exception then
                try {
                    @SuppressWarnings("unchecked") Class<? extends Throwable> clazz = (Class<? extends Throwable>) classLoader.loadClass(errorPage.getError());
                    deployment.addErrorPage(new ErrorPage(errorPage.getLocation(), clazz));
                } catch (ClassNotFoundException cnfe) {
                    cnfe.addSuppressed(nfe);
                    throw new IllegalArgumentException("Unsupported error: " + errorPage.getError(), cnfe);
                }
            }
        }
    }
    if (contextModel.getContextParams() != null) {
        for (Map.Entry<String, String> entry : contextModel.getContextParams().entrySet()) {
            deployment.addInitParameter(entry.getKey(), entry.getValue());
        }
    }
    Bundle bundle = contextModel.getBundle();
    ServletContainerInitializerScanner scanner = new ServletContainerInitializerScanner(bundle, undertowBundle, packageAdminTracker.getService());
    Map<ServletContainerInitializer, Set<Class<?>>> containerInitializers = contextModel.getContainerInitializers();
    if (containerInitializers == null) {
        containerInitializers = new HashMap<>();
        contextModel.setContainerInitializers(containerInitializers);
    }
    scanner.scanBundles(containerInitializers);
    for (Entry<ServletContainerInitializer, Set<Class<?>>> entry : contextModel.getContainerInitializers().entrySet()) {
        deployment.addServletContainerInitalizer(new ServletContainerInitializerInfo(clazz(null, entry.getKey()), factory(null, entry.getKey()), entry.getValue()));
    }
    for (FilterModel filter : filters) {
        FilterInfo info = new FilterInfo(filter.getName(), clazz(filter.getFilterClass(), filter.getFilter()), factory(filter.getFilterClass(), filter.getFilter()));
        for (Map.Entry<String, String> param : filter.getInitParams().entrySet()) {
            info.addInitParam(param.getKey(), param.getValue());
        }
        info.setAsyncSupported(filter.isAsyncSupported());
        deployment.addFilter(info);
        String[] dispatchers = filter.getDispatcher();
        if (dispatchers == null || dispatchers.length == 0) {
            dispatchers = new String[] { "request" };
        }
        for (String dispatcher : dispatchers) {
            DispatcherType dt = DispatcherType.valueOf(dispatcher.toUpperCase());
            String[] servletNames = filter.getServletNames();
            if (servletNames != null) {
                for (String servletName : servletNames) {
                    deployment.addFilterServletNameMapping(filter.getName(), servletName, dt);
                }
            }
            String[] urlPatterns = filter.getUrlPatterns();
            if (urlPatterns != null) {
                for (String urlPattern : urlPatterns) {
                    deployment.addFilterUrlMapping(filter.getName(), urlPattern, dt);
                }
            }
        }
    }
    for (SecurityConstraintMappingModel securityConstraintMapping : securityConstraintMappings) {
        SecurityConstraint info = new SecurityConstraint();
        // if (securityConstraintMapping.isAuthentication()) {
        // info.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.AUTHENTICATE);
        // }
        info.addRolesAllowed(securityConstraintMapping.getRoles());
        String dataConstraint = securityConstraintMapping.getDataConstraint();
        if (dataConstraint == null || "NONE".equals(dataConstraint)) {
            info.setTransportGuaranteeType(TransportGuaranteeType.NONE);
        } else if ("INTEGRAL".equals(dataConstraint)) {
            info.setTransportGuaranteeType(TransportGuaranteeType.INTEGRAL);
        } else {
            info.setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL);
        }
        WebResourceCollection wr = new WebResourceCollection();
        if (securityConstraintMapping.getMapping() != null) {
            wr.addHttpMethod(securityConstraintMapping.getMapping());
        }
        if (securityConstraintMapping.getUrl() != null) {
            wr.addUrlPattern(securityConstraintMapping.getUrl());
        }
        info.addWebResourceCollection(wr);
        deployment.addSecurityConstraint(info);
    }
    for (EventListenerModel listener : eventListeners) {
        ListenerInfo info = new ListenerInfo(clazz(null, listener.getEventListener()), factory(null, listener.getEventListener()));
        deployment.addListener(info);
    }
    if (isJspAvailable()) {
        // use JasperClassloader
        try {
            @SuppressWarnings("unchecked") Class<ServletContainerInitializer> clazz = (Class<ServletContainerInitializer>) classLoader.loadClass("org.ops4j.pax.web.jsp.JasperInitializer");
            deployment.addServletContainerInitalizer(new ServletContainerInitializerInfo(clazz, factory(clazz, null), null));
        } catch (ClassNotFoundException e) {
            // LOG.error("Unable to load JasperInitializer", e);
            e.printStackTrace();
        }
    }
    if (isWebSocketAvailable()) {
        wsXnioWorker = UndertowUtil.createWorker(contextModel.getClassLoader());
        if (wsXnioWorker != null) {
            deployment.addServletContextAttribute(io.undertow.websockets.jsr.WebSocketDeploymentInfo.ATTRIBUTE_NAME, new io.undertow.websockets.jsr.WebSocketDeploymentInfo().setWorker(wsXnioWorker).setBuffers(new DefaultByteBufferPool(true, 100)));
        }
    }
    // Add HttpContext security support
    deployment.addInnerHandlerChainWrapper(new HandlerWrapper() {

        @Override
        public HttpHandler wrap(final HttpHandler handler) {
            return exchange -> {
                // Verify security
                ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                if (contextModel.getHttpContext().handleSecurity(src.getOriginalRequest(), src.getOriginalResponse())) {
                    handler.handleRequest(exchange);
                } else {
                    // the rest of the contexts
                    try {
                        src.getOriginalResponse().sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    } catch (IllegalStateException e) {
                        try {
                            src.getOriginalResponse().setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        } catch (IllegalStateException ee) {
                        // Ignore
                        }
                    }
                }
            };
        }
    });
    ServletSessionConfig ssc = new ServletSessionConfig();
    if (contextModel.getSessionDomain() != null) {
        ssc.setDomain(contextModel.getSessionDomain());
    } else if (configuration != null && configuration.getSessionDomain() != null) {
        ssc.setDomain(configuration.getSessionDomain());
    }
    if (contextModel.getSessionCookie() != null) {
        ssc.setName(contextModel.getSessionCookie());
    } else if (configuration != null && configuration.getSessionCookie() != null) {
        ssc.setName(configuration.getSessionCookie());
    }
    if (contextModel.getSessionCookieHttpOnly() != null) {
        ssc.setHttpOnly(contextModel.getSessionCookieHttpOnly());
    } else if (configuration != null && configuration.getSessionCookieHttpOnly() != null) {
        ssc.setHttpOnly(configuration.getSessionCookieHttpOnly());
    }
    if (contextModel.getSessionCookieSecure() != null) {
        ssc.setSecure(contextModel.getSessionCookieSecure());
    } else if (configuration != null && configuration.getSessionCookieSecure() != null) {
        ssc.setSecure(configuration.getSessionCookieSecure());
    }
    if (contextModel.getSessionCookieMaxAge() != null) {
        ssc.setMaxAge(contextModel.getSessionCookieMaxAge());
    } else if (configuration != null && configuration.getSessionCookieMaxAge() != null) {
        ssc.setMaxAge(configuration.getSessionCookieMaxAge());
    }
    if (contextModel.getSessionPath() != null) {
        ssc.setPath(contextModel.getSessionPath());
    } else if (configuration != null && configuration.getSessionPath() != null) {
        ssc.setPath(configuration.getSessionPath());
    }
    deployment.setServletSessionConfig(ssc);
    deployment.setDefaultSessionTimeout(defaultSessionTimeoutInMinutes * 60);
    deployment.setSessionPersistenceManager(sessionPersistenceManager);
    manager = container.addDeployment(deployment);
    LOG.info("Creating undertow servlet deployment for context path /{}...", contextModel.getContextName());
    manager.deploy();
    LOG.info("Creating undertow servlet deployment for context path /{} - done", contextModel.getContextName());
    LOG.info("Registering {} as OSGi service...", manager.getDeployment().getServletContext());
    registerServletContext(manager.getDeployment().getServletContext(), bundle);
    LOG.info("Registering {} as OSGi service - done", manager.getDeployment().getServletContext());
    if (consumer != null) {
        consumer.accept(manager.getDeployment().getServletContext());
    }
    LOG.info("Starting Undertow web application for context path /{}", contextModel.getContextName());
    handler = manager.start();
}
Also used : WebResourceCollection(io.undertow.servlet.api.WebResourceCollection) ErrorPage(io.undertow.servlet.api.ErrorPage) ServletInfo(io.undertow.servlet.api.ServletInfo) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) ResourceModel(org.ops4j.pax.web.service.spi.model.ResourceModel) WebContainerContext(org.ops4j.pax.web.service.WebContainerContext) DispatcherType(javax.servlet.DispatcherType) HttpHandler(io.undertow.server.HttpHandler) SecurityConstraintMappingModel(org.ops4j.pax.web.service.spi.model.SecurityConstraintMappingModel) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) FilterModel(org.ops4j.pax.web.service.spi.model.FilterModel) EventListenerModel(org.ops4j.pax.web.service.spi.model.EventListenerModel) ListenerInfo(io.undertow.servlet.api.ListenerInfo) ServletSessionConfig(io.undertow.servlet.api.ServletSessionConfig) HandlerWrapper(io.undertow.server.HandlerWrapper) ServletModel(org.ops4j.pax.web.service.spi.model.ServletModel) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) WelcomeFileModel(org.ops4j.pax.web.service.spi.model.WelcomeFileModel) LoginConfig(io.undertow.servlet.api.LoginConfig) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) FilterInfo(io.undertow.servlet.api.FilterInfo) ServletContainerInitializerInfo(io.undertow.servlet.api.ServletContainerInitializerInfo) ServletContainerInitializerScanner(org.ops4j.pax.web.utils.ServletContainerInitializerScanner) ErrorPageModel(org.ops4j.pax.web.service.spi.model.ErrorPageModel) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) ServletExtension(io.undertow.servlet.ServletExtension)

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