Search in sources :

Example 41 with ServletRequestContext

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

the class JASPICAuthenticationMechanism method authenticate.

@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext sc) {
    exchange.putAttachment(AUTH_RUN, true);
    final ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    final JASPIServerAuthenticationManager sam = createJASPIAuthenticationManager();
    final GenericMessageInfo messageInfo = createMessageInfo(exchange, sc);
    final String applicationIdentifier = buildApplicationIdentifier(requestContext);
    final JASPICallbackHandler cbh = new JASPICallbackHandler();
    exchange.putAttachment(JASPICContext.ATTACHMENT_KEY, new JASPICContext(messageInfo, sam, cbh));
    UndertowLogger.ROOT_LOGGER.debugf("validateRequest for layer [%s] and applicationContextIdentifier [%s]", JASPI_HTTP_SERVLET_LAYER, applicationIdentifier);
    Account cachedAccount = null;
    final JASPICSecurityContext jaspicSecurityContext = (JASPICSecurityContext) exchange.getSecurityContext();
    final AuthenticatedSessionManager sessionManager = exchange.getAttachment(AuthenticatedSessionManager.ATTACHMENT_KEY);
    if (sessionManager != null) {
        AuthenticatedSessionManager.AuthenticatedSession authSession = sessionManager.lookupSession(exchange);
        if (authSession != null) {
            cachedAccount = authSession.getAccount();
            // SAM modules via request.getUserPrincipal().
            if (cachedAccount != null) {
                jaspicSecurityContext.setCachedAuthenticatedAccount(cachedAccount);
            }
        }
    }
    AuthenticationMechanismOutcome outcome = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    Account authenticatedAccount = null;
    boolean isValid = sam.isValid(messageInfo, new Subject(), JASPI_HTTP_SERVLET_LAYER, applicationIdentifier, cbh);
    jaspicSecurityContext.setCachedAuthenticatedAccount(null);
    if (isValid) {
        // The CBH filled in the JBOSS SecurityContext, we need to create an Undertow account based on that
        org.jboss.security.SecurityContext jbossSct = SecurityActions.getSecurityContext();
        authenticatedAccount = createAccount(cachedAccount, jbossSct);
        updateSubjectRoles(jbossSct);
    }
    // authType resolution (check message info first, then check for the configured auth method, then use mech-specific name).
    String authType = (String) messageInfo.getMap().get(JASPI_AUTH_TYPE);
    if (authType == null)
        authType = this.configuredAuthMethod != null ? this.configuredAuthMethod : MECHANISM_NAME;
    if (isValid && authenticatedAccount != null) {
        outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
        Object registerObj = messageInfo.getMap().get(JASPI_REGISTER_SESSION);
        boolean cache = false;
        if (registerObj != null && (registerObj instanceof String)) {
            cache = Boolean.valueOf((String) registerObj);
        }
        sc.authenticationComplete(authenticatedAccount, authType, cache);
    } else if (isValid && authenticatedAccount == null && !isMandatory(requestContext)) {
        outcome = AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    } else {
        outcome = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        sc.authenticationFailed("JASPIC authentication failed.", authType);
        // make sure we don't return status OK if the AuthException was thrown
        if (wasAuthExceptionThrown(exchange) && !statusIndicatesError(exchange)) {
            exchange.setResponseCode(DEFAULT_ERROR_CODE);
        }
    }
    // A SAM can wrap the HTTP request/response objects - update the servlet request context with the values found in the message info.
    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    servletRequestContext.setServletRequest((HttpServletRequest) messageInfo.getRequestMessage());
    servletRequestContext.setServletResponse((HttpServletResponse) messageInfo.getResponseMessage());
    return outcome;
}
Also used : Account(io.undertow.security.idm.Account) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) Subject(javax.security.auth.Subject) GenericMessageInfo(org.jboss.security.auth.message.GenericMessageInfo) AuthenticatedSessionManager(io.undertow.security.api.AuthenticatedSessionManager) JASPICallbackHandler(org.jboss.security.auth.callback.JASPICallbackHandler) JASPIServerAuthenticationManager(org.jboss.security.plugins.auth.JASPIServerAuthenticationManager)

Example 42 with ServletRequestContext

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

the class JASPICSecurityContext method buildMessageInfo.

/**
     * <p>
     * Builds the {@code MessageInfo} instance for the {@code cleanSubject()} call.
     * </p>
     *
     * @return the constructed {@code MessageInfo} object.
     */
private MessageInfo buildMessageInfo() {
    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    GenericMessageInfo messageInfo = new GenericMessageInfo();
    messageInfo.setRequestMessage(servletRequestContext.getServletRequest());
    messageInfo.setResponseMessage(servletRequestContext.getServletResponse());
    // when calling cleanSubject, isMandatory must be set to true.
    messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory", "true");
    return messageInfo;
}
Also used : ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) GenericMessageInfo(org.jboss.security.auth.message.GenericMessageInfo)

Example 43 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project datawave-spring-boot-starter by NationalSecurityAgency.

the class UndertowCustomizer method customize.

@Override
public void customize(ConfigurableUndertowWebServerFactory factory) {
    serverProperties = applicationContext.getBean(ServerProperties.class);
    datawaveServerProperties = applicationContext.getBean(DatawaveServerProperties.class);
    // @formatter:off
    factory.addBuilderCustomizers(c -> {
        // Ensure that the request start time is set on the request by Undertow
        c.setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true);
        if (useDaemonThreads) {
            // Tell XNIO to use Daemon threads
            c.setWorkerOption(Options.THREAD_DAEMON, true);
        }
        if (factory instanceof AbstractConfigurableWebServerFactory) {
            AbstractConfigurableWebServerFactory undertowFactory = (AbstractConfigurableWebServerFactory) factory;
            // If we're using ssl and also want a non-secure listener, then add it here since the parent won't configure both
            if (serverProperties.getSsl() != null && serverProperties.getSsl().isEnabled() && datawaveServerProperties.getNonSecurePort() != null && datawaveServerProperties.getNonSecurePort() >= 0) {
                String host = undertowFactory.getAddress() == null ? "0.0.0.0" : undertowFactory.getAddress().getHostAddress();
                c.addHttpListener(datawaveServerProperties.getNonSecurePort(), host);
            }
        }
    });
    factory.addDeploymentInfoCustomizers(deploymentInfo -> {
        // Use the initial handler chain to set the request start time as early as possible in the call chain.
        // The ServletRequestContext won't be set on the exchange just yet, though, so we'll need to copy that
        // attribute onto the ServletRequest on the inner handler wrapper.
        deploymentInfo.addInitialHandlerChainWrapper(httpHandler -> httpServerExchange -> {
            if (httpServerExchange.getRequestStartTime() == -1) {
                Connectors.setRequestStartTime(httpServerExchange);
            }
            httpHandler.handleRequest(httpServerExchange);
        });
        deploymentInfo.addInnerHandlerChainWrapper(httpHandler -> httpServerExchange -> {
            ServletRequestContext ctx = httpServerExchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
            if (ctx != null) {
                ServletRequest servletRequest = ctx.getServletRequest();
                if (servletRequest != null) {
                    servletRequest.setAttribute(REQUEST_START_TIME_NS_ATTRIBUTE, httpServerExchange.getRequestStartTime());
                } else {
                    logger.warn("ServletRequest is null on the ServletRequestContext.");
                }
            } else {
                logger.warn("ServletRequestContext could not be found on the HttpServerExchange.");
            }
            httpHandler.handleRequest(httpServerExchange);
        });
    });
// @formatter:on
}
Also used : ServletRequest(javax.servlet.ServletRequest) ServerProperties(org.springframework.boot.autoconfigure.web.ServerProperties) AbstractConfigurableWebServerFactory(org.springframework.boot.web.server.AbstractConfigurableWebServerFactory) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Example 44 with ServletRequestContext

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

the class GlobalRequestControllerHandler method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    RunResult result = entryPoint.beginRequest();
    try {
        if (result == RunResult.RUN) {
            next.handleRequest(exchange);
        } else {
            boolean allowed = false;
            for (Predicate allow : allowSuspendedRequests) {
                if (allow.resolve(exchange)) {
                    allowed = true;
                    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                    if (src != null) {
                        src.getServletRequest().setAttribute(ORG_WILDFLY_SUSPENDED, "true");
                    }
                    next.handleRequest(exchange);
                    break;
                }
            }
            if (!allowed) {
                exchange.setStatusCode(503);
                exchange.endExchange();
            }
        }
    } finally {
        if (result == RunResult.RUN && (exchange.isComplete() || !exchange.isDispatched())) {
            entryPoint.requestComplete();
        } else if (result == RunResult.RUN) {
            exchange.addExchangeCompleteListener(listener);
        }
    }
}
Also used : ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) RunResult(org.wildfly.extension.requestcontroller.RunResult) Predicate(io.undertow.predicate.Predicate)

Example 45 with ServletRequestContext

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

the class RequestDispatcherImpl method forwardImplSetup.

private void forwardImplSetup(final ServletRequest request, final ServletResponse response) throws ServletException, IOException {
    final ServletRequestContext servletRequestContext = SecurityActions.currentServletRequestContext();
    if (servletRequestContext == null) {
        UndertowLogger.REQUEST_LOGGER.debugf("No servlet request context for %s, dispatching mock request", request);
        mock(request, response);
        return;
    }
    ServletContextImpl oldServletContext = null;
    HttpSessionImpl oldSession = null;
    if (servletRequestContext.getCurrentServletContext() != this.servletContext) {
        try {
            // cross context request, we need to run the thread setup actions
            oldServletContext = servletRequestContext.getCurrentServletContext();
            oldSession = servletRequestContext.getSession();
            servletRequestContext.setSession(null);
            servletRequestContext.setCurrentServletContext(this.servletContext);
            this.servletContext.invokeAction(servletRequestContext.getExchange(), new ThreadSetupHandler.Action<Void, Object>() {

                @Override
                public Void call(HttpServerExchange exchange, Object context) throws Exception {
                    forwardImpl(request, response, servletRequestContext);
                    return null;
                }
            });
        } finally {
            servletRequestContext.setSession(oldSession);
            servletRequestContext.setCurrentServletContext(oldServletContext);
            // update time in old context and run the requestDone for the session
            servletRequestContext.getCurrentServletContext().updateSessionAccessTime(servletRequestContext.getExchange());
        }
    } else {
        forwardImpl(request, response, servletRequestContext);
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) ServletException(jakarta.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException)

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