Search in sources :

Example 1 with SecurityContext

use of io.undertow.security.api.SecurityContext in project wildfly by wildfly.

the class HTTPSchemeServerAuthModule method validateRequest.

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
    HttpServerExchange exchange = (HttpServerExchange) messageInfo.getMap().get(JASPICAuthenticationMechanism.HTTP_SERVER_EXCHANGE_ATTACHMENT_KEY);
    SecurityContext securityContext = (SecurityContext) messageInfo.getMap().get(JASPICAuthenticationMechanism.SECURITY_CONTEXT_ATTACHMENT_KEY);
    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    List<AuthenticationMechanism> mechanisms = src.getDeployment().getAuthenticationMechanisms();
    try {
        boolean success = false;
        for (AuthenticationMechanism mechanism : mechanisms) {
            AuthenticationMechanism.AuthenticationMechanismOutcome result = mechanism.authenticate(exchange, securityContext);
            if (result == AUTHENTICATED) {
                success = true;
                break;
            } else if (result == NOT_AUTHENTICATED) {
                break;
            }
        }
        if (!success) {
            String mandatory = (String) messageInfo.getMap().get("javax.security.auth.message.MessagePolicy.isMandatory");
            if (mandatory != null && mandatory.toLowerCase().equals("false")) {
                return SUCCESS;
            } else {
                for (AuthenticationMechanism mechanism : mechanisms) {
                    AuthenticationMechanism.ChallengeResult challengeResult = mechanism.sendChallenge(exchange, securityContext);
                    if (challengeResult.getDesiredResponseCode() != null) {
                        exchange.setResponseCode(challengeResult.getDesiredResponseCode());
                    }
                    if (exchange.isResponseComplete()) {
                        break;
                    }
                }
                return SEND_CONTINUE;
            }
        }
    } catch (Exception e) {
        UndertowLogger.ROOT_LOGGER.debug(e);
        throw new AuthException("Could not validateRequest using mechanisms [" + mechanisms + ".");
    }
    return SUCCESS;
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) JASPICAuthenticationMechanism(org.wildfly.extension.undertow.security.jaspi.JASPICAuthenticationMechanism) AuthenticationMechanism(io.undertow.security.api.AuthenticationMechanism) SecurityContext(io.undertow.security.api.SecurityContext) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) AuthException(javax.security.auth.message.AuthException) AuthException(javax.security.auth.message.AuthException)

Example 2 with SecurityContext

use of io.undertow.security.api.SecurityContext in project undertow by undertow-io.

the class AsyncWebSocketHttpServerExchange method getUserPrincipal.

@Override
public Principal getUserPrincipal() {
    SecurityContext sc = exchange.getSecurityContext();
    if (sc == null) {
        return null;
    }
    Account authenticatedAccount = sc.getAuthenticatedAccount();
    if (authenticatedAccount == null) {
        return null;
    }
    return authenticatedAccount.getPrincipal();
}
Also used : Account(io.undertow.security.idm.Account) SecurityContext(io.undertow.security.api.SecurityContext)

Example 3 with SecurityContext

use of io.undertow.security.api.SecurityContext in project undertow by undertow-io.

the class RequestDumpingHandler method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final StringBuilder sb = new StringBuilder();
    // Log pre-service information
    final SecurityContext sc = exchange.getSecurityContext();
    sb.append("\n----------------------------REQUEST---------------------------\n");
    sb.append("               URI=" + exchange.getRequestURI() + "\n");
    sb.append(" characterEncoding=" + exchange.getRequestHeaders().get(Headers.CONTENT_ENCODING) + "\n");
    sb.append("     contentLength=" + exchange.getRequestContentLength() + "\n");
    sb.append("       contentType=" + exchange.getRequestHeaders().get(Headers.CONTENT_TYPE) + "\n");
    //sb.append("       contextPath=" + exchange.getContextPath());
    if (sc != null) {
        if (sc.isAuthenticated()) {
            sb.append("          authType=" + sc.getMechanismName() + "\n");
            sb.append("         principle=" + sc.getAuthenticatedAccount().getPrincipal() + "\n");
        } else {
            sb.append("          authType=none" + "\n");
        }
    }
    Map<String, Cookie> cookies = exchange.getRequestCookies();
    if (cookies != null) {
        for (Map.Entry<String, Cookie> entry : cookies.entrySet()) {
            Cookie cookie = entry.getValue();
            sb.append("            cookie=" + cookie.getName() + "=" + cookie.getValue() + "\n");
        }
    }
    for (HeaderValues header : exchange.getRequestHeaders()) {
        for (String value : header) {
            sb.append("            header=" + header.getHeaderName() + "=" + value + "\n");
        }
    }
    sb.append("            locale=" + LocaleUtils.getLocalesFromHeader(exchange.getRequestHeaders().get(Headers.ACCEPT_LANGUAGE)) + "\n");
    sb.append("            method=" + exchange.getRequestMethod() + "\n");
    Map<String, Deque<String>> pnames = exchange.getQueryParameters();
    for (Map.Entry<String, Deque<String>> entry : pnames.entrySet()) {
        String pname = entry.getKey();
        Iterator<String> pvalues = entry.getValue().iterator();
        sb.append("         parameter=");
        sb.append(pname);
        sb.append('=');
        while (pvalues.hasNext()) {
            sb.append(pvalues.next());
            if (pvalues.hasNext()) {
                sb.append(", ");
            }
        }
        sb.append("\n");
    }
    //sb.append("          pathInfo=" + exchange.getPathInfo());
    sb.append("          protocol=" + exchange.getProtocol() + "\n");
    sb.append("       queryString=" + exchange.getQueryString() + "\n");
    sb.append("        remoteAddr=" + exchange.getSourceAddress() + "\n");
    sb.append("        remoteHost=" + exchange.getSourceAddress().getHostName() + "\n");
    //sb.append("requestedSessionId=" + exchange.getRequestedSessionId());
    sb.append("            scheme=" + exchange.getRequestScheme() + "\n");
    sb.append("              host=" + exchange.getRequestHeaders().getFirst(Headers.HOST) + "\n");
    sb.append("        serverPort=" + exchange.getDestinationAddress().getPort() + "\n");
    //sb.append("       servletPath=" + exchange.getServletPath());
    //sb.append("          isSecure=" + exchange.isSecure());
    exchange.addExchangeCompleteListener(new ExchangeCompletionListener() {

        @Override
        public void exchangeEvent(final HttpServerExchange exchange, final NextListener nextListener) {
            // Log post-service information
            sb.append("--------------------------RESPONSE--------------------------\n");
            if (sc != null) {
                if (sc.isAuthenticated()) {
                    sb.append("          authType=" + sc.getMechanismName() + "\n");
                    sb.append("         principle=" + sc.getAuthenticatedAccount().getPrincipal() + "\n");
                } else {
                    sb.append("          authType=none" + "\n");
                }
            }
            sb.append("     contentLength=" + exchange.getResponseContentLength() + "\n");
            sb.append("       contentType=" + exchange.getResponseHeaders().getFirst(Headers.CONTENT_TYPE) + "\n");
            Map<String, Cookie> cookies = exchange.getResponseCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies.values()) {
                    sb.append("            cookie=" + cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain() + "; path=" + cookie.getPath() + "\n");
                }
            }
            for (HeaderValues header : exchange.getResponseHeaders()) {
                for (String value : header) {
                    sb.append("            header=" + header.getHeaderName() + "=" + value + "\n");
                }
            }
            sb.append("            status=" + exchange.getStatusCode() + "\n");
            String storedResponse = StoredResponse.INSTANCE.readAttribute(exchange);
            if (storedResponse != null) {
                sb.append("body=\n");
                sb.append(storedResponse);
            }
            sb.append("==============================================================");
            nextListener.proceed();
            UndertowLogger.REQUEST_DUMPER_LOGGER.info(sb.toString());
        }
    });
    // Perform the exchange
    next.handleRequest(exchange);
}
Also used : HeaderValues(io.undertow.util.HeaderValues) Deque(java.util.Deque) HttpServerExchange(io.undertow.server.HttpServerExchange) SecurityContext(io.undertow.security.api.SecurityContext) ExchangeCompletionListener(io.undertow.server.ExchangeCompletionListener) Map(java.util.Map)

Example 4 with SecurityContext

use of io.undertow.security.api.SecurityContext in project undertow by undertow-io.

the class JDBCLogHandler method logMessage.

public void logMessage(String pattern, HttpServerExchange exchange) {
    JDBCLogAttribute jdbcLogAttribute = new JDBCLogAttribute();
    if (pattern.equals("combined")) {
        jdbcLogAttribute.pattern = pattern;
    }
    jdbcLogAttribute.remoteHost = ((InetSocketAddress) exchange.getConnection().getPeerAddress()).getAddress().getHostAddress();
    SecurityContext sc = exchange.getSecurityContext();
    if (sc == null || !sc.isAuthenticated()) {
        jdbcLogAttribute.user = null;
    } else {
        jdbcLogAttribute.user = sc.getAuthenticatedAccount().getPrincipal().getName();
    }
    jdbcLogAttribute.query = exchange.getQueryString();
    jdbcLogAttribute.bytes = exchange.getResponseContentLength();
    if (jdbcLogAttribute.bytes < 0) {
        jdbcLogAttribute.bytes = 0;
    }
    jdbcLogAttribute.status = exchange.getStatusCode();
    if (jdbcLogAttribute.pattern.equals("combined")) {
        jdbcLogAttribute.virtualHost = exchange.getRequestHeaders().getFirst(Headers.HOST);
        jdbcLogAttribute.method = exchange.getRequestMethod().toString();
        jdbcLogAttribute.referer = exchange.getRequestHeaders().getFirst(Headers.REFERER);
        jdbcLogAttribute.userAgent = exchange.getRequestHeaders().getFirst(Headers.USER_AGENT);
    }
    this.pendingMessages.add(jdbcLogAttribute);
    int state = stateUpdater.get(this);
    if (state == 0) {
        if (stateUpdater.compareAndSet(this, 0, 1)) {
            this.executor = exchange.getConnection().getWorker();
            this.executor.execute(this);
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SecurityContext(io.undertow.security.api.SecurityContext)

Example 5 with SecurityContext

use of io.undertow.security.api.SecurityContext in project undertow by undertow-io.

the class AuthenticationConstraintHandler method handleRequest.

/**
     * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
     */
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (isAuthenticationRequired(exchange)) {
        SecurityContext context = exchange.getSecurityContext();
        UndertowLogger.SECURITY_LOGGER.debugf("Setting authentication required for exchange %s", exchange);
        context.setAuthenticationRequired();
    }
    next.handleRequest(exchange);
}
Also used : SecurityContext(io.undertow.security.api.SecurityContext)

Aggregations

SecurityContext (io.undertow.security.api.SecurityContext)18 Account (io.undertow.security.idm.Account)4 ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)4 HttpServerExchange (io.undertow.server.HttpServerExchange)3 HttpSession (javax.servlet.http.HttpSession)2 Undertow (io.undertow.Undertow)1 AuthenticatedSessionManager (io.undertow.security.api.AuthenticatedSessionManager)1 AuthenticatedSession (io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession)1 AuthenticationMechanism (io.undertow.security.api.AuthenticationMechanism)1 AuthenticationMechanismContext (io.undertow.security.api.AuthenticationMechanismContext)1 IdentityManager (io.undertow.security.idm.IdentityManager)1 ExchangeCompletionListener (io.undertow.server.ExchangeCompletionListener)1 HttpHandler (io.undertow.server.HttpHandler)1 Session (io.undertow.server.session.Session)1 SessionConfig (io.undertow.server.session.SessionConfig)1 SessionManager (io.undertow.server.session.SessionManager)1 AuthorizationManager (io.undertow.servlet.api.AuthorizationManager)1 Deployment (io.undertow.servlet.api.Deployment)1 SingleConstraintMatch (io.undertow.servlet.api.SingleConstraintMatch)1 ServletChain (io.undertow.servlet.handlers.ServletChain)1