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

The following examples show how to use io.undertow.server.HttpServerExchange#getRequestScheme() . 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: CorsUtil.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Determine the default origin, to allow for local access.
 * @param exchange the current HttpExchange.
 * @return the default origin (aka current server).
 */
public static String defaultOrigin(HttpServerExchange exchange) {
    String host = NetworkUtils.formatPossibleIpv6Address(exchange.getHostName());
    String protocol = exchange.getRequestScheme();
    int port = exchange.getHostPort();
    //This browser set header should not need IPv6 escaping
    StringBuilder allowedOrigin = new StringBuilder(256);
    allowedOrigin.append(protocol).append("://").append(host);
    if (!isDefaultPort(port, protocol)) {
        allowedOrigin.append(':').append(port);
    }
    return allowedOrigin.toString();
}
 
Example 2
Source File: CorsUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine the default origin, to allow for local access.
 * @param exchange the current HttpExchange.
 * @return the default origin (aka current server).
 */
public static String defaultOrigin(HttpServerExchange exchange) {
    String host = NetworkUtils.formatPossibleIpv6Address(exchange.getHostName());
    String protocol = exchange.getRequestScheme();
    int port = exchange.getHostPort();
    //This browser set header should not need IPv6 escaping
    StringBuilder allowedOrigin = new StringBuilder(256);
    allowedOrigin.append(protocol).append("://").append(host);
    if (!isDefaultPort(port, protocol)) {
        allowedOrigin.append(':').append(port);
    }
    return allowedOrigin.toString();
}
 
Example 3
Source File: AbstractSamlAuthMech.java    From keycloak with Apache License 2.0 5 votes vote down vote up
static void sendRedirect(final HttpServerExchange exchange, final String location) {
    if (location == null) {
        LOG.log(Level.WARNING, "Logout page not set.");
        exchange.setStatusCode(StatusCodes.NOT_FOUND);
        exchange.endExchange();
        return;
    }

    if (PROTOCOL_PATTERN.matcher(location).find()) {
        exchange.getResponseHeaders().put(Headers.LOCATION, location);
    } else {
        String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + location;
        exchange.getResponseHeaders().put(Headers.LOCATION, loc);
    }
}
 
Example 4
Source File: FormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
static void sendRedirect(final HttpServerExchange exchange, final String location) {
    // TODO - String concatenation to construct URLS is extremely error prone - switch to a URI which will better handle this.
    String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + location;
    exchange.setResponseHeader(HttpHeaderNames.LOCATION, loc);
}
 
Example 5
Source File: RequestSchemeAttribute.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    return exchange.getRequestScheme();
}
 
Example 6
Source File: RedirectBuilder.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
/**
 * Redirects to a new relative path. All other data from the exchange is preserved.
 *
 * @param exchange          The HTTP server exchange
 * @param newRelativePath   The new relative path
 * @param includeParameters If query and path parameters from the exchange should be included
 * @return
 */
public static String redirect(final HttpServerExchange exchange, final String newRelativePath, final boolean includeParameters) {
    try {
        StringBuilder uri = new StringBuilder(exchange.getRequestScheme());
        uri.append("://");
        uri.append(exchange.getHostAndPort());
        uri.append(encodeUrlPart(exchange.getResolvedPath()));
        if (exchange.getResolvedPath().endsWith("/")) {
            if (newRelativePath.startsWith("/")) {
                uri.append(encodeUrlPart(newRelativePath.substring(1)));
            } else {
                uri.append(encodeUrlPart(newRelativePath));
            }
        } else {
            if (!newRelativePath.startsWith("/")) {
                uri.append('/');
            }
            uri.append(encodeUrlPart(newRelativePath));
        }
        if (includeParameters) {
            if (!exchange.getPathParameters().isEmpty()) {
                boolean first = true;
                uri.append(';');
                for (Map.Entry<String, Deque<String>> param : exchange.getPathParameters().entrySet()) {
                    for (String value : param.getValue()) {
                        if (first) {
                            first = false;
                        } else {
                            uri.append('&');
                        }
                        uri.append(URLEncoder.encode(param.getKey(), UTF_8));
                        uri.append('=');
                        uri.append(URLEncoder.encode(value, UTF_8));
                    }
                }
            }
            if (!exchange.getQueryString().isEmpty()) {
                uri.append('?');
                uri.append(exchange.getQueryString());
            }
        }
        return uri.toString();
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: FormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
static void sendRedirect(final HttpServerExchange exchange, final String location) {
    // TODO - String concatenation to construct URLS is extremely error prone - switch to a URI which will better handle this.
    String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + location;
    exchange.getResponseHeaders().put(Headers.LOCATION, loc);
}
 
Example 8
Source File: RequestSchemeAttribute.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    return exchange.getRequestScheme();
}
 
Example 9
Source File: RedirectBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Redirects to a new relative path. All other data from the exchange is preserved.
 *
 * @param exchange          The HTTP server exchange
 * @param newRelativePath   The new relative path
 * @param includeParameters If query and path parameters from the exchange should be included
 * @return
 */
public static String redirect(final HttpServerExchange exchange, final String newRelativePath, final boolean includeParameters) {
    try {
        StringBuilder uri = new StringBuilder(exchange.getRequestScheme());
        uri.append("://");
        uri.append(exchange.getHostAndPort());
        uri.append(encodeUrlPart(exchange.getResolvedPath()));
        if (exchange.getResolvedPath().endsWith("/")) {
            if (newRelativePath.startsWith("/")) {
                uri.append(encodeUrlPart(newRelativePath.substring(1)));
            } else {
                uri.append(encodeUrlPart(newRelativePath));
            }
        } else {
            if (!newRelativePath.startsWith("/")) {
                uri.append('/');
            }
            uri.append(encodeUrlPart(newRelativePath));
        }
        if (includeParameters) {
            if (!exchange.getPathParameters().isEmpty()) {
                boolean first = true;
                uri.append(';');
                for (Map.Entry<String, Deque<String>> param : exchange.getPathParameters().entrySet()) {
                    for (String value : param.getValue()) {
                        if (first) {
                            first = false;
                        } else {
                            uri.append('&');
                        }
                        uri.append(URLEncoder.encode(param.getKey(), UTF_8));
                        uri.append('=');
                        uri.append(URLEncoder.encode(value, UTF_8));
                    }
                }
            }
            if (!exchange.getQueryString().isEmpty()) {
                uri.append('?');
                uri.append(exchange.getQueryString());
            }
        }
        return uri.toString();
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: LightFormAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
static void sendRedirect(final HttpServerExchange exchange, final String location) {
    // TODO - String concatenation to construct URLS is extremely error prone - switch to a URI which will better handle this.
    String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + location;
    exchange.getResponseHeaders().put(Headers.LOCATION, loc);
}
 
Example 11
Source File: LogoutHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final HeaderMap requestHeaders = exchange.getRequestHeaders();
    final HeaderMap responseHeaders = exchange.getResponseHeaders();

    String referrer = responseHeaders.getFirst(REFERER);
    String protocol = exchange.getRequestScheme();
    String host = null;
    if (referrer != null) {
        try {
            URI uri = new URI(referrer);
            protocol = uri.getScheme();
            host = uri.getHost() + portPortion(protocol, uri.getPort());
        } catch (URISyntaxException e) {
        }
    }
    if (host == null) {
        host = requestHeaders.getFirst(HOST);
        if (host == null) {
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            return;
        }
    }

    /*
     * Main sequence of events:
     *
     * 1. Redirect to self using user:pass@host form of authority. This forces Safari to overwrite its cache. (Also
     * forces FF and Chrome, but not absolutely necessary) Set the exit flag as a state signal for step 3
     *
     * 2. Send 401 digest without a nonce stale marker, this will force FF and Chrome and likely other browsers to
     * assume an invalid (old) password. In the case of Opera, which doesn't invalidate under such a circumstance,
     * send an invalid realm. This will overwrite its auth cache, since it indexes it by host and not realm.
     *
     * 3. The credentials in 307 redirect wlll be transparently accepted and a final redirect to the console is
     * performed. Opera ignores these, so the user must hit escape which will use javascript to perform the redirect
     *
     * In the case of Internet Explorer, all of this will be bypassed and will simply redirect to the console. The console
     * MUST use a special javascript call before redirecting to logout.
     */
    String userAgent = requestHeaders.getFirst(USER_AGENT);
    boolean opera = userAgent != null && userAgent.contains("Opera");
    boolean win = !opera && userAgent != null && (userAgent.contains("MSIE") || userAgent.contains("Trident"));

    String rawQuery = exchange.getQueryString();
    boolean exit = rawQuery != null && rawQuery.contains(EXIT);



    if (win) {
        responseHeaders.add(LOCATION, protocol + "://" + host + "/");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } else {
        // Do the redirects to finish the logout
        String authorization = requestHeaders.getFirst(AUTHORIZATION);

        boolean digest = true;
        Map<String, Deque<String>> parameters = exchange.getQueryParameters();
        if (parameters.containsKey(MECHANISM)) {
            digest = !BASIC.equals(parameters.get(MECHANISM).getFirst());
        }
        if (authorization != null && authorization.length() > BASIC.length()
                && BASIC.equalsIgnoreCase(authorization.substring(0, BASIC.length()))) {
            digest = false;
            ByteBuffer decode = FlexBase64.decode(authorization.substring(6));
            authorization = new String(decode.array(), decode.arrayOffset(), decode.limit(), UTF_8);
        }

        if (authorization == null || !authorization.contains("enter-login-here")) {
            if (!exit) {
                responseHeaders.add(LOCATION, protocol + "://enter-login-here:blah@" + host + "/logout?" + EXIT + "&"
                        + MECHANISM + "=" + (digest ? DIGEST : BASIC));
                exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
                return;
            }

            mechanism(opera, digest).sendChallenge(exchange, null);
            String reply = "<html><script type='text/javascript'>window.location=\"" + protocol + "://" + host
                    + "/\";</script></html>";
            exchange.setStatusCode(StatusCodes.UNAUTHORIZED);
            exchange.getResponseSender().send(reply, IoCallback.END_EXCHANGE);
            return;
        }

        // Success, now back to the login screen
        responseHeaders.add(LOCATION, protocol + "://" + host + "/");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    }
}
 
Example 12
Source File: AbstractUndertowKeycloakAuthMech.java    From keycloak with Apache License 2.0 4 votes vote down vote up
static void sendRedirect(final HttpServerExchange exchange, final String location) {
    // TODO - String concatenation to construct URLS is extremely error prone - switch to a URI which will better handle this.
    String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + location;
    exchange.getResponseHeaders().put(Headers.LOCATION, loc);
}