Java Code Examples for io.undertow.server.HttpServerExchange#getRequestHeader()

The following examples show how to use io.undertow.server.HttpServerExchange#getRequestHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RedirectDirHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final String path = exchange.getRelativePath();
    final ServletPathMatch info = paths.getServletHandlerByPath(path);
    // https://issues.jboss.org/browse/WFLY-3439
    // if the request is an upgrade request then we don't want to redirect
    // as there is a good chance the web socket client won't understand the redirect
    // we make an exception for HTTP2 upgrade requests, as this would have already be handled at
    // the connector level if it was going to be handled.
    String upgradeString = exchange.getRequestHeader(HttpHeaderNames.UPGRADE);
    boolean isUpgradeRequest = upgradeString != null && !upgradeString.startsWith(HTTP2_UPGRADE_PREFIX);
    if (info.getType() == ServletPathMatch.Type.REDIRECT && !isUpgradeRequest) {
        // UNDERTOW-89
        // we redirect on GET requests to the root context to add an / to the end
        if (exchange.getRequestMethod().equals(HttpMethodNames.GET) || exchange.getRequestMethod().equals(HttpMethodNames.GET)) {
            exchange.setStatusCode(StatusCodes.FOUND);
        } else {
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
        }
        exchange.setResponseHeader(HttpHeaderNames.LOCATION, RedirectBuilder.redirect(exchange, exchange.getRelativePath() + "/", true));
        return;
    }
    next.handleRequest(exchange);
}
 
Example 2
Source File: LearningPushHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String fullPath;
    String requestPath;
    if(exchange.getQueryString().isEmpty()) {
        fullPath = exchange.getRequestURL();
        requestPath = exchange.getRequestPath();
    } else{
        fullPath = exchange.getRequestURL() + "?" + exchange.getQueryString();
        requestPath = exchange.getRequestPath() + "?" + exchange.getQueryString();
    }

    doPush(exchange, fullPath);
    String referrer = exchange.getRequestHeader(HttpHeaderNames.REFERER);
    if (referrer != null) {
        String accept = exchange.getRequestHeader(HttpHeaderNames.ACCEPT);
        if (accept == null || !accept.contains("text/html")) {
            //if accept contains text/html it generally means the user has clicked
            //a link to move to a new page, and is not a resource load for the current page
            //we only care about resources for the current page

            exchange.addExchangeCompleteListener(new PushCompletionListener(fullPath, requestPath, referrer));
        }
    }
    next.handleRequest(exchange);
}
 
Example 3
Source File: MultiPartParserDefinition.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private MultiPartUploadHandler(final HttpServerExchange exchange, final String boundary, final long maxIndividualFileSize, final long fileSizeThreshold, final String defaultEncoding) {
    this.exchange = exchange;
    this.maxIndividualFileSize = maxIndividualFileSize;
    this.defaultEncoding = defaultEncoding;
    this.fileSizeThreshold = fileSizeThreshold;
    this.data = new FormData(exchange.getUndertowOptions().get(UndertowOptions.MAX_PARAMETERS, 1000));
    String charset = defaultEncoding;
    String contentType = exchange.getRequestHeader(HttpHeaderNames.CONTENT_TYPE);
    if (contentType != null) {
        String value = HttpHeaderNames.extractQuotedValueFromHeader(contentType, "charset");
        if (value != null) {
            charset = value;
        }
    }
    this.parser = MultipartParser.beginParse(exchange, this, boundary.getBytes(StandardCharsets.US_ASCII), charset);

}
 
Example 4
Source File: FormEncodedDataDefinition.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public FormDataParser create(final HttpServerExchange exchange) {
    String mimeType = exchange.getRequestHeader(HttpHeaderNames.CONTENT_TYPE);
    if (forceCreation || (mimeType != null && mimeType.startsWith(APPLICATION_X_WWW_FORM_URLENCODED))) {

        String charset = defaultEncoding;
        String contentType = exchange.getRequestHeader(HttpHeaderNames.CONTENT_TYPE);
        if (contentType != null) {
            String cs = HttpHeaderNames.extractQuotedValueFromHeader(contentType, "charset");
            if (cs != null) {
                charset = cs;
            }
        }
        UndertowLogger.REQUEST_LOGGER.tracef("Created form encoded parser for %s", exchange);
        return new FormEncodedDataParser(charset, exchange);
    }
    return null;
}
 
Example 5
Source File: NameVirtualHostHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final String hostHeader = exchange.getRequestHeader(HttpHeaderNames.HOST);
    if (hostHeader != null) {
        String host;
        if (hostHeader.contains(":")) { //header can be in host:port format
            host = hostHeader.substring(0, hostHeader.lastIndexOf(":"));
        } else {
            host = hostHeader;
        }
        //most hosts will be lowercase, so we do the host
        HttpHandler handler = hosts.get(host);
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
        //do a cache insensitive match
        handler = hosts.get(host.toLowerCase(Locale.ENGLISH));
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
    }
    defaultHandler.handleRequest(exchange);
}
 
Example 6
Source File: SSLHeaderHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final String sessionId = exchange.getRequestHeader(SSL_SESSION_ID);
    final String cipher = exchange.getRequestHeader(SSL_CIPHER);
    String clientCert = exchange.getRequestHeader(SSL_CLIENT_CERT);
    //the proxy client replaces \n with ' '
    if (clientCert != null && clientCert.length() > 28) {
        StringBuilder sb = new StringBuilder(clientCert.length() + 1);
        sb.append(Certificates.BEGIN_CERT);
        sb.append('\n');
        sb.append(clientCert.replace(' ', '\n').substring(28, clientCert.length() - 26));//core certificate data
        sb.append('\n');
        sb.append(Certificates.END_CERT);
        clientCert = sb.toString();
    }
    if (clientCert != null || sessionId != null || cipher != null) {
        try {
            SSLSessionInfo info = new BasicSSLSessionInfo(sessionId, cipher, clientCert);
            exchange.setRequestScheme(HTTPS);
            exchange.setSslSessionInfo(info);
        } catch (java.security.cert.CertificateException | CertificateException e) {
            UndertowLogger.REQUEST_LOGGER.debugf(e, "Could not create certificate from header %s", clientCert);
        }
    }
    next.handleRequest(exchange);
}
 
Example 7
Source File: GSSAPIAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private String getHostName(final HttpServerExchange exchange) {
    String hostName = exchange.getRequestHeader(HOST);
    if (hostName != null) {
        if (hostName.startsWith("[") && hostName.contains("]")) {
            hostName = hostName.substring(0, hostName.indexOf(']') + 1);
        } else if (hostName.contains(":")) {
            hostName = hostName.substring(0, hostName.indexOf(":"));
        }
        return hostName;
    }

    return null;
}
 
Example 8
Source File: BasicAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
    if(silent) {
        //if this is silent we only send a challenge if the request contained auth headers
        //otherwise we assume another method will send the challenge
        String authHeader = exchange.getRequestHeader(AUTHORIZATION);
        if(authHeader == null) {
            return ChallengeResult.NOT_SENT;
        }
    }
    exchange.addResponseHeader(WWW_AUTHENTICATE, challenge);
    UndertowLogger.SECURITY_LOGGER.debugf("Sending basic auth challenge %s for %s", challenge, exchange);
    return new ChallengeResult(true, UNAUTHORIZED);
}
 
Example 9
Source File: GenericHeaderAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private String getPrincipal(HttpServerExchange exchange) {
    for (String header : identityHeaders) {
        String res = exchange.getRequestHeader(header);
        if (res != null) {
            return res;
        }
    }
    return null;
}
 
Example 10
Source File: JDBCLogHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void logMessage(String pattern, HttpServerExchange exchange) {
    JDBCLogAttribute jdbcLogAttribute = new JDBCLogAttribute();

    if (pattern.equals("combined")) {
        jdbcLogAttribute.pattern = pattern;
    }
    jdbcLogAttribute.remoteHost = ((InetSocketAddress) exchange.getSourceAddress()).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.getRequestHeader(HttpHeaderNames.HOST);
        jdbcLogAttribute.method = exchange.getRequestMethod();
        jdbcLogAttribute.referer = exchange.getRequestHeader(HttpHeaderNames.REFERER);
        jdbcLogAttribute.userAgent = exchange.getRequestHeader(HttpHeaderNames.USER_AGENT);
    }

    this.pendingMessages.add(jdbcLogAttribute);
    int state = stateUpdater.get(this);
    if (state == 0) {
        if (stateUpdater.compareAndSet(this, 0, 1)) {
            this.executor = exchange.getWorker();
            this.executor.execute(this);
        }
    }
}
 
Example 11
Source File: BasicAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
/**
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {

    List<String> authHeaders = exchange.getRequestHeaders(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {

                String base64Challenge = current.substring(PREFIX_LENGTH);
                String plainChallenge = null;
                try {
                    ByteBuf decode = FlexBase64.decode(base64Challenge);

                    Charset charset = this.charset;
                    if(!userAgentCharsets.isEmpty()) {
                        String ua = exchange.getRequestHeader(HttpHeaderNames.USER_AGENT);
                        if(ua != null) {
                            for (Map.Entry<Pattern, Charset> entry : userAgentCharsets.entrySet()) {
                                if(entry.getKey().matcher(ua).find()) {
                                    charset = entry.getValue();
                                    break;
                                }
                            }
                        }
                    }

                    plainChallenge = new String(decode.array(), decode.arrayOffset(), decode.writerIndex(), charset);
                    UndertowLogger.SECURITY_LOGGER.debugf("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, exchange);
                } catch (IOException e) {
                    UndertowLogger.SECURITY_LOGGER.debugf(e, "Failed to decode basic auth header %s in %s", base64Challenge, exchange);
                }
                int colonPos;
                if (plainChallenge != null && (colonPos = plainChallenge.indexOf(COLON)) > -1) {
                    String userName = plainChallenge.substring(0, colonPos);
                    char[] password = plainChallenge.substring(colonPos + 1).toCharArray();

                    IdentityManager idm = getIdentityManager(securityContext);
                    PasswordCredential credential = new PasswordCredential(password);
                    try {
                        final AuthenticationMechanismOutcome result;
                        Account account = idm.verify(userName, credential);
                        if (account != null) {
                            securityContext.authenticationComplete(account, name, false);
                            result = AuthenticationMechanismOutcome.AUTHENTICATED;
                        } else {
                            securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
                            result = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
                        }
                        return result;
                    } finally {
                        clear(password);
                    }
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}