Java Code Examples for io.undertow.util.HeaderMap#add()

The following examples show how to use io.undertow.util.HeaderMap#add() . 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: CorsUtilTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Test of matchOrigin method, of class CorsUtil.
 */
@Test
public void testMatchOrigin() throws Exception {
    HeaderMap headerMap = new HeaderMap();
    headerMap.add(HOST, "localhost:80");
    headerMap.add(ORIGIN, "http://localhost");
    HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10);
    exchange.setRequestScheme("http");
    exchange.setRequestMethod(HttpString.EMPTY);
    Collection<String> allowedOrigins = null;
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
    allowedOrigins = Collections.singletonList("http://www.example.com:9990");
    //Default origin
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
    headerMap.clear();
    headerMap.add(HOST, "localhost:80");
    headerMap.add(ORIGIN, "http://www.example.com:9990");
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://www.example.com:9990"));
    headerMap.clear();
    headerMap.add(HOST, "localhost:80");
    headerMap.add(ORIGIN, "http://www.example.com");
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is(nullValue()));
    headerMap.addAll(ORIGIN, Arrays.asList("http://localhost:8080", "http://www.example.com:9990", "http://localhost"));
    allowedOrigins = Arrays.asList("http://localhost", "http://www.example.com:9990");
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
}
 
Example 2
Source File: CorsUtilTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Test of defaultOrigin method, of class CorsUtil.
 */
@Test
public void testDefaultOrigin() {
    HeaderMap headerMap = new HeaderMap();
    headerMap.add(HOST, "localhost:80");
    HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10);
    exchange.setRequestScheme("http");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://localhost"));
    headerMap.clear();
    headerMap.add(HOST, "www.example.com:8080");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://www.example.com:8080"));
    headerMap.clear();
    headerMap.add(HOST, "www.example.com:443");
    exchange.setRequestScheme("https");
    assertThat(CorsUtil.defaultOrigin(exchange), is("https://www.example.com"));
    headerMap.clear();
    exchange.setRequestScheme("http");
    headerMap.add(HOST, "[::1]:80");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://[::1]"));
}
 
Example 3
Source File: CorsUtilTest.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test of matchOrigin method, of class CorsUtil.
 */
@Test
public void testMatchOrigin() throws Exception {
    HeaderMap headerMap = new HeaderMap();
    headerMap.add(HOST, "localhost:80");
    headerMap.add(ORIGIN, "http://localhost");
    HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10);
    exchange.setRequestScheme("http");
    Collection<String> allowedOrigins = null;
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
    allowedOrigins = Collections.singletonList("http://www.example.com:9990");
    //Default origin
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
    headerMap.clear();
    headerMap.add(HOST, "localhost:80");
    headerMap.add(ORIGIN, "http://www.example.com:9990");
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://www.example.com:9990"));
    headerMap.clear();
    headerMap.add(HOST, "localhost:80");
    headerMap.add(ORIGIN, "http://www.example.com");
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is(nullValue()));
    headerMap.addAll(ORIGIN, Arrays.asList("http://localhost:8080", "http://www.example.com:9990", "http://localhost"));
    allowedOrigins = Arrays.asList("http://localhost", "http://www.example.com:9990");
    assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
}
 
Example 4
Source File: CorsUtilTest.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test of defaultOrigin method, of class CorsUtil.
 */
@Test
public void testDefaultOrigin() {
    HeaderMap headerMap = new HeaderMap();
    headerMap.add(HOST, "localhost:80");
    HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10);
    exchange.setRequestScheme("http");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://localhost"));
    headerMap.clear();
    headerMap.add(HOST, "www.example.com:8080");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://www.example.com:8080"));
    headerMap.clear();
    headerMap.add(HOST, "www.example.com:443");
    exchange.setRequestScheme("https");
    assertThat(CorsUtil.defaultOrigin(exchange), is("https://www.example.com"));
    headerMap.clear();
    exchange.setRequestScheme("http");
    headerMap.add(HOST, "[::1]:80");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://[::1]"));
}
 
Example 5
Source File: DatawaveAuthenticationMechanism.java    From datawave with Apache License 2.0 5 votes vote down vote up
private void addTimingRequestHeaders(HttpServerExchange exchange) {
    long requestStartTime = exchange.getRequestStartTime();
    long loginTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - requestStartTime);
    HeaderMap headers = exchange.getRequestHeaders();
    headers.add(HEADER_START_TIME, requestStartTime);
    headers.add(HEADER_LOGIN_TIME, loginTime);
}
 
Example 6
Source File: DigestAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ChallengeResult sendChallenge(final HttpServerExchange exchange, final SecurityContext securityContext) {
    DigestContext context = exchange.getAttachment(DigestContext.ATTACHMENT_KEY);
    boolean stale = context == null ? false : context.isStale();

    StringBuilder rb = new StringBuilder(DIGEST_PREFIX);
    rb.append(Headers.REALM.toString()).append("=\"").append(realmName).append("\",");
    rb.append(Headers.DOMAIN.toString()).append("=\"").append(domain).append("\",");
    // based on security constraints.
    rb.append(Headers.NONCE.toString()).append("=\"").append(nonceManager.nextNonce(null, exchange)).append("\",");
    // Not currently using OPAQUE as it offers no integrity, used for session data leaves it vulnerable to
    // session fixation type issues as well.
    rb.append(Headers.OPAQUE.toString()).append("=\"00000000000000000000000000000000\"");
    if (stale) {
        rb.append(",stale=true");
    }
    if (supportedAlgorithms.size() > 0) {
        // This header will need to be repeated once for each algorithm.
        rb.append(",").append(Headers.ALGORITHM.toString()).append("=%s");
    }
    if (qopString != null) {
        rb.append(",").append(Headers.QOP.toString()).append("=\"").append(qopString).append("\"");
    }

    String theChallenge = rb.toString();
    HeaderMap responseHeader = exchange.getResponseHeaders();
    if (supportedAlgorithms.isEmpty()) {
        responseHeader.add(WWW_AUTHENTICATE, theChallenge);
    } else {
        for (DigestAlgorithm current : supportedAlgorithms) {
            responseHeader.add(WWW_AUTHENTICATE, String.format(theChallenge, current.getToken()));
        }
    }

    return new ChallengeResult(true, UNAUTHORIZED);
}
 
Example 7
Source File: DigestAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void sendAuthenticationInfoHeader(final HttpServerExchange exchange) {
    DigestContext context = exchange.getAttachment(DigestContext.ATTACHMENT_KEY);
    DigestQop qop = context.getQop();
    String currentNonce = context.getNonce();
    String nextNonce = nonceManager.nextNonce(currentNonce, exchange);
    if (qop != null || !nextNonce.equals(currentNonce)) {
        StringBuilder sb = new StringBuilder();
        sb.append(NEXT_NONCE).append("=\"").append(nextNonce).append("\"");
        if (qop != null) {
            Map<DigestAuthorizationToken, String> parsedHeader = context.getParsedHeader();
            sb.append(",").append(Headers.QOP.toString()).append("=\"").append(qop.getToken()).append("\"");
            byte[] ha1 = context.getHa1();
            byte[] ha2;

            if (qop == DigestQop.AUTH) {
                ha2 = createHA2Auth(context);
            } else {
                ha2 = createHA2AuthInt();
            }
            String rspauth = new String(createRFC2617RequestDigest(ha1, ha2, context), StandardCharsets.UTF_8);
            sb.append(",").append(Headers.RESPONSE_AUTH.toString()).append("=\"").append(rspauth).append("\"");
            sb.append(",").append(Headers.CNONCE.toString()).append("=\"").append(parsedHeader.get(DigestAuthorizationToken.CNONCE)).append("\"");
            sb.append(",").append(Headers.NONCE_COUNT.toString()).append("=").append(parsedHeader.get(DigestAuthorizationToken.NONCE_COUNT));
        }

        HeaderMap responseHeader = exchange.getResponseHeaders();
        responseHeader.add(AUTHENTICATION_INFO, sb.toString());
    }

    exchange.removeAttachment(DigestContext.ATTACHMENT_KEY);
}
 
Example 8
Source File: Http2ServerConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected StreamSinkConduit getSinkConduit(HttpServerExchange exchange, StreamSinkConduit conduit) {
    HeaderMap headers = responseChannel.getHeaders();
    DateUtils.addDateHeaderIfRequired(exchange);
    headers.add(STATUS, exchange.getStatusCode());
    Connectors.flattenCookies(exchange);
    return originalSinkConduit;
}
 
Example 9
Source File: CustomResourceHandler.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    super.handleRequest(exchange);

    HeaderMap headers = exchange.getResponseHeaders();
    if (cacheEnabled) headers.add(Headers.CACHE_CONTROL, "private, no-cache");
    else headers.add(Headers.CACHE_CONTROL, "private, no-store, no-cache");
}
 
Example 10
Source File: UndertowXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static void addHttpHeaders(ClientRequest request, HttpHeaders headers) {
	HeaderMap headerMap = request.getRequestHeaders();
	for (String name : headers.keySet()) {
		for (String value : headers.get(name)) {
			headerMap.add(HttpString.tryFromString(name), value);
		}
	}
}
 
Example 11
Source File: StaticHeadersHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
void apply(HttpServerExchange exchange, Predicate<String> putHeader) {
    HeaderMap headers = exchange.getResponseHeaders();
    if (putHeader.test(headerName.toString())) {
        headers.put(headerName, value);
    } else {
        headers.add(headerName, value);
    }
}
 
Example 12
Source File: AccessLogCompletionListenerTest.java    From galeb with Apache License 2.0 4 votes vote down vote up
private HeaderMap getRequestHeaders() {
    HeaderMap headerMap = new HeaderMap();
    headerMap.add(HttpString.tryFromString("HOST"),"vhost.host.virtual");
    return headerMap;
}
 
Example 13
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 14
Source File: UndertowHTTPDestinationTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void setUpDoService(boolean setRedirectURL,
                            boolean sendResponse,
                            boolean decoupled,
                            String method,
                            String query,
                            int status
                            ) throws Exception {

    is = EasyMock.createMock(ServletInputStream.class);
    os = EasyMock.createMock(ServletOutputStream.class);
    request = EasyMock.createMock(HttpServletRequest.class);
    response = EasyMock.createMock(HttpServletResponse.class);
    request.getMethod();
    EasyMock.expectLastCall().andReturn(method).atLeastOnce();
    request.getUserPrincipal();
    EasyMock.expectLastCall().andReturn(null).anyTimes();

    if (setRedirectURL) {
        policy.setRedirectURL(NOWHERE + "foo/bar");
        response.sendRedirect(EasyMock.eq(NOWHERE + "foo/bar"));
        EasyMock.expectLastCall();
        response.flushBuffer();
        EasyMock.expectLastCall();
        EasyMock.expectLastCall();
    } else {
        //getQueryString for if statement
        request.getQueryString();
        EasyMock.expectLastCall().andReturn(query);

        if ("GET".equals(method) && "?wsdl".equals(query)) {
            verifyGetWSDLQuery();
        } else { // test for the post
            EasyMock.expect(request.getAttribute(AbstractHTTPDestination.CXF_CONTINUATION_MESSAGE))
                .andReturn(null);


            EasyMock.expect(request.getInputStream()).andReturn(is);
            EasyMock.expect(request.getContextPath()).andReturn("/bar");
            EasyMock.expect(request.getServletPath()).andReturn("");
            EasyMock.expect(request.getPathInfo()).andReturn("/foo");
            EasyMock.expect(request.getRequestURI()).andReturn("/foo");
            EasyMock.expect(request.getRequestURL())
                .andReturn(new StringBuffer("http://localhost/foo")).anyTimes();
            EasyMock.expect(request.getCharacterEncoding()).andReturn(StandardCharsets.UTF_8.name());
            EasyMock.expect(request.getQueryString()).andReturn(query);
            EasyMock.expect(request.getHeader("Accept")).andReturn("*/*");
            EasyMock.expect(request.getContentType()).andReturn("text/xml charset=utf8").times(2);
            EasyMock.expect(request.getAttribute("http.service.redirection")).andReturn(null).anyTimes();

            HeaderMap httpFields = new HeaderMap();
            httpFields.add(new HttpString("content-type"), "text/xml");
            httpFields.add(new HttpString("content-type"), "charset=utf8");
            httpFields.put(new HttpString(UndertowHTTPDestinationTest.AUTH_HEADER),
                           UndertowHTTPDestinationTest.BASIC_AUTH);
            List<String> headers = new ArrayList<>();
            for (HttpString header : httpFields.getHeaderNames()) {
                headers.add(header.toString());
            }
            EasyMock.expect(request.getHeaderNames()).andReturn(Collections.enumeration(headers));
            request.getHeaders("content-type");
            EasyMock.expectLastCall().andReturn(Collections.enumeration(httpFields.get("content-type")));
            request.getHeaders(UndertowHTTPDestinationTest.AUTH_HEADER);
            EasyMock.expectLastCall().andReturn(Collections.enumeration(
                                                httpFields.get(UndertowHTTPDestinationTest.AUTH_HEADER)));

            EasyMock.expect(request.getInputStream()).andReturn(is);
            EasyMock.expectLastCall();
            response.flushBuffer();
            EasyMock.expectLastCall();
            if (sendResponse) {
                response.setStatus(status);
                EasyMock.expectLastCall();
                response.setContentType("text/xml charset=utf8");
                EasyMock.expectLastCall();
                response.addHeader(EasyMock.isA(String.class), EasyMock.isA(String.class));
                EasyMock.expectLastCall().anyTimes();
                response.setContentLength(0);
                EasyMock.expectLastCall().anyTimes();
                response.getOutputStream();
                EasyMock.expectLastCall().andReturn(os);
                response.getStatus();
                EasyMock.expectLastCall().andReturn(status).anyTimes();
                response.flushBuffer();
                EasyMock.expectLastCall();
            }
            request.getAttribute("javax.servlet.request.cipher_suite");
            EasyMock.expectLastCall().andReturn("anythingwilldoreally");
            request.getAttribute("javax.net.ssl.session");
            EasyMock.expectLastCall().andReturn(null);
            request.getAttribute("javax.servlet.request.X509Certificate");
            EasyMock.expectLastCall().andReturn(null);
        }
    }

    if (decoupled) {
        setupDecoupledBackChannel();
    }
    EasyMock.replay(response);
    EasyMock.replay(request);
}