Search in sources :

Example 56 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.

the class ForwardedHeaderTransformerTests method forwardedHeader.

@Test
void forwardedHeader() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Forwarded", "host=84.198.58.199;proto=https");
    ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
    assertThat(request.getURI()).isEqualTo(new URI("https://84.198.58.199/path"));
    assertForwardedHeadersRemoved(request);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) MockServerHttpRequest(org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) URI(java.net.URI) Test(org.junit.jupiter.api.Test)

Example 57 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.

the class ForwardedHeaderTransformerTests method xForwardedFor.

@Test
public void xForwardedFor() throws URISyntaxException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("x-forwarded-for", "203.0.113.195, 70.41.3.18, 150.172.238.178");
    ServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb")).headers(headers).build();
    request = this.requestMutator.apply(request);
    assertThat(request.getRemoteAddress()).isNotNull();
    assertThat(request.getRemoteAddress().getHostName()).isEqualTo("203.0.113.195");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) MockServerHttpRequest(org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) URI(java.net.URI) Test(org.junit.jupiter.api.Test)

Example 58 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.

the class ForwardedHeaderTransformer method apply.

/**
 * Apply and remove, or remove Forwarded type headers.
 * @param request the request
 */
@Override
public ServerHttpRequest apply(ServerHttpRequest request) {
    if (hasForwardedHeaders(request)) {
        ServerHttpRequest.Builder builder = request.mutate();
        if (!this.removeOnly) {
            URI uri = UriComponentsBuilder.fromHttpRequest(request).build(true).toUri();
            builder.uri(uri);
            String prefix = getForwardedPrefix(request);
            if (prefix != null) {
                builder.path(prefix + uri.getRawPath());
                builder.contextPath(prefix);
            }
            InetSocketAddress remoteAddress = request.getRemoteAddress();
            remoteAddress = UriComponentsBuilder.parseForwardedFor(request, remoteAddress);
            if (remoteAddress != null) {
                builder.remoteAddress(remoteAddress);
            }
        }
        removeForwardedHeaders(builder);
        request = builder.build();
    }
    return request;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) URI(java.net.URI)

Example 59 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.

the class AbstractMessageReaderArgumentResolver method readBody.

/**
 * Read the body from a method argument with {@link HttpMessageReader}.
 * @param bodyParam represents the element type for the body
 * @param actualParam the actual method argument type; possibly different
 * from {@code bodyParam}, e.g. for an {@code HttpEntity} argument
 * @param isBodyRequired true if the body is required
 * @param bindingContext the binding context to use
 * @param exchange the current exchange
 * @return a Mono with the value to use for the method argument
 * @since 5.0.2
 */
protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParameter actualParam, boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {
    ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParam);
    ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
    Class<?> resolvedType = bodyType.resolve();
    ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
    ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
    isBodyRequired = isBodyRequired || (adapter != null && !adapter.supportsEmpty());
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    MediaType contentType = request.getHeaders().getContentType();
    MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
    Object[] hints = extractValidationHints(bodyParam);
    if (mediaType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Form data is accessed via ServerWebExchange.getFormData() in WebFlux.");
        }
        return Mono.error(new ResponseStatusException(HttpStatus.UNSUPPORTED_MEDIA_TYPE));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(exchange.getLogPrefix() + (contentType != null ? "Content-Type:" + contentType : "No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
    }
    for (HttpMessageReader<?> reader : getMessageReaders()) {
        if (reader.canRead(elementType, mediaType)) {
            Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
            if (adapter != null && adapter.isMultiValue()) {
                if (logger.isDebugEnabled()) {
                    logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
                }
                Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
                flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
                if (isBodyRequired) {
                    flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
                }
                if (hints != null) {
                    flux = flux.doOnNext(target -> validate(target, hints, bodyParam, bindingContext, exchange));
                }
                return Mono.just(adapter.fromPublisher(flux));
            } else {
                // Single-value (with or without reactive type wrapper)
                if (logger.isDebugEnabled()) {
                    logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
                }
                Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
                mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
                if (isBodyRequired) {
                    mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
                }
                if (hints != null) {
                    mono = mono.doOnNext(target -> validate(target, hints, bodyParam, bindingContext, exchange));
                }
                return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
            }
        }
    }
    // No compatible reader but body may be empty..
    HttpMethod method = request.getMethod();
    if (contentType == null && SUPPORTED_METHODS.contains(method)) {
        Flux<DataBuffer> body = request.getBody().doOnNext(buffer -> {
            DataBufferUtils.release(buffer);
            // Body not empty, back toy 415..
            throw new UnsupportedMediaTypeStatusException(mediaType, getSupportedMediaTypes(elementType), elementType);
        });
        if (isBodyRequired) {
            body = body.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
        }
        return (adapter != null ? Mono.just(adapter.fromPublisher(body)) : Mono.from(body));
    }
    return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, getSupportedMediaTypes(elementType), elementType));
}
Also used : ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) Validator(org.springframework.validation.Validator) Conventions(org.springframework.core.Conventions) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) ServerWebInputException(org.springframework.web.server.ServerWebInputException) DecodingException(org.springframework.core.codec.DecodingException) Hints(org.springframework.core.codec.Hints) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) BindingContext(org.springframework.web.reactive.BindingContext) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) HandlerMethodArgumentResolverSupport(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Nullable(org.springframework.lang.Nullable) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) ReactiveAdapter(org.springframework.core.ReactiveAdapter) ResponseStatusException(org.springframework.web.server.ResponseStatusException) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) ValidationAnnotationUtils(org.springframework.validation.annotation.ValidationAnnotationUtils) Set(java.util.Set) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Flux(reactor.core.publisher.Flux) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) Annotation(java.lang.annotation.Annotation) Assert(org.springframework.util.Assert) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) ResponseStatusException(org.springframework.web.server.ResponseStatusException) ReactiveAdapter(org.springframework.core.ReactiveAdapter) HttpMethod(org.springframework.http.HttpMethod) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 60 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.

the class RequestMappingInfoHandlerMapping method handleNoMatch.

/**
 * Iterate all RequestMappingInfos once again, look if any match by URL at
 * least and raise exceptions accordingly.
 * @throws MethodNotAllowedException for matches by URL but not by HTTP method
 * @throws UnsupportedMediaTypeStatusException if there are matches by URL
 * and HTTP method but not by consumable media types
 * @throws NotAcceptableStatusException if there are matches by URL and HTTP
 * method but not by producible media types
 * @throws ServerWebInputException if there are matches by URL and HTTP
 * method but not by query parameter conditions
 */
@Override
protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> infos, ServerWebExchange exchange) throws Exception {
    PartialMatchHelper helper = new PartialMatchHelper(infos, exchange);
    if (helper.isEmpty()) {
        return null;
    }
    ServerHttpRequest request = exchange.getRequest();
    if (helper.hasMethodsMismatch()) {
        HttpMethod httpMethod = request.getMethod();
        Set<HttpMethod> methods = helper.getAllowedMethods();
        if (HttpMethod.OPTIONS.equals(httpMethod)) {
            Set<MediaType> mediaTypes = helper.getConsumablePatchMediaTypes();
            HttpOptionsHandler handler = new HttpOptionsHandler(methods, mediaTypes);
            return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
        }
        throw new MethodNotAllowedException(httpMethod, methods);
    }
    if (helper.hasConsumesMismatch()) {
        Set<MediaType> mediaTypes = helper.getConsumableMediaTypes();
        MediaType contentType;
        try {
            contentType = request.getHeaders().getContentType();
        } catch (InvalidMediaTypeException ex) {
            throw new UnsupportedMediaTypeStatusException(ex.getMessage());
        }
        throw new UnsupportedMediaTypeStatusException(contentType, new ArrayList<>(mediaTypes), exchange.getRequest().getMethod());
    }
    if (helper.hasProducesMismatch()) {
        Set<MediaType> mediaTypes = helper.getProducibleMediaTypes();
        throw new NotAcceptableStatusException(new ArrayList<>(mediaTypes));
    }
    if (helper.hasParamsMismatch()) {
        throw new ServerWebInputException("Unsatisfied query parameter conditions: " + helper.getParamConditions() + ", actual parameters: " + request.getQueryParams());
    }
    return null;
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) ServerWebInputException(org.springframework.web.server.ServerWebInputException) MethodNotAllowedException(org.springframework.web.server.MethodNotAllowedException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Aggregations

ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)71 HttpHeaders (org.springframework.http.HttpHeaders)26 Test (org.junit.jupiter.api.Test)25 MockServerHttpRequest (org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest)20 ServerWebExchange (org.springframework.web.server.ServerWebExchange)19 URI (java.net.URI)17 ServerHttpResponse (org.springframework.http.server.reactive.ServerHttpResponse)17 Mono (reactor.core.publisher.Mono)13 MockServerHttpRequest (org.springframework.mock.http.server.reactive.MockServerHttpRequest)10 HandshakeInfo (org.springframework.web.reactive.socket.HandshakeInfo)9 HttpMethod (org.springframework.http.HttpMethod)8 ArrayList (java.util.ArrayList)7 List (java.util.List)6 Map (java.util.Map)6 HttpStatus (org.springframework.http.HttpStatus)6 MediaType (org.springframework.http.MediaType)6 Flux (reactor.core.publisher.Flux)6 Principal (java.security.Principal)5 Collections (java.util.Collections)5 HashMap (java.util.HashMap)5