Search in sources :

Example 36 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;
        }
        UndertowSession session = new UndertowSession(channel, URI.create(exchange.getRequestURI()), 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(javax.websocket.server.ServerEndpointConfig) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) HttpServletRequest(javax.servlet.http.HttpServletRequest) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) Endpoint(javax.websocket.Endpoint) InstanceHandle(io.undertow.servlet.api.InstanceHandle) ImmediateInstanceHandle(io.undertow.servlet.util.ImmediateInstanceHandle) Principal(java.security.Principal)

Example 37 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 38 with ServletRequestContext

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

the class JASPICAuthenticationMechanism method createMessageInfo.

private GenericMessageInfo createMessageInfo(final HttpServerExchange exchange, final SecurityContext securityContext) {
    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    GenericMessageInfo messageInfo = new GenericMessageInfo();
    messageInfo.setRequestMessage(servletRequestContext.getServletRequest());
    messageInfo.setResponseMessage(servletRequestContext.getServletResponse());
    messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory", isMandatory(servletRequestContext).toString());
    // additional context data, useful to provide access to Undertow resources during the modules processing
    messageInfo.getMap().put(SECURITY_CONTEXT_ATTACHMENT_KEY, securityContext);
    messageInfo.getMap().put(HTTP_SERVER_EXCHANGE_ATTACHMENT_KEY, exchange);
    return messageInfo;
}
Also used : ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) GenericMessageInfo(org.jboss.security.auth.message.GenericMessageInfo)

Example 39 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 40 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)

Aggregations

ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)40 IOException (java.io.IOException)8 Session (io.undertow.server.session.Session)5 HttpSessionImpl (io.undertow.servlet.spec.HttpSessionImpl)5 ServletException (javax.servlet.ServletException)5 SecurityContext (io.undertow.security.api.SecurityContext)4 Account (io.undertow.security.idm.Account)4 HttpServerExchange (io.undertow.server.HttpServerExchange)4 HttpString (io.undertow.util.HttpString)4 ServletRequest (javax.servlet.ServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Subject (javax.security.auth.Subject)3 GenericMessageInfo (org.jboss.security.auth.message.GenericMessageInfo)3 AuthenticatedSessionManager (io.undertow.security.api.AuthenticatedSessionManager)2 Resource (io.undertow.server.handlers.resource.Resource)2 ResourceManager (io.undertow.server.handlers.resource.ResourceManager)2 AuthorizationManager (io.undertow.servlet.api.AuthorizationManager)2 SingleConstraintMatch (io.undertow.servlet.api.SingleConstraintMatch)2