spring-cloud-gateway icon indicating copy to clipboard operation
spring-cloud-gateway copied to clipboard

Reques body is removed from request when accessed (spring-cloud-gateway-mvc)

Open bsgrd opened this issue 1 year ago • 1 comments

Describe the bug When I try to read or modify the request body in spring-cloud-gateway-mvc, the body is removed from the request and this exception is thrown:

java.lang.NullPointerException: Cannot invoke "java.util.Map.put(Object, Object)" because the return value of "org.springframework.cloud.gateway.server.mvc.common.MvcUtils.getGatewayAttributes(org.springframework.web.servlet.function.ServerRequest)" is null

I'm using Spring Boot 3.2.2 and cloud 2023.0.0

Sample I have tried using the BeforeFilterFunctions.modifyRequestBody: .before(modifyRequestBody(String.class, String.class, MediaType.APPLICATION_JSON_VALUE, (serverRequest, s) -> s))

.. and also a regular filter like this:

.filter((request, next) -> {
	byte[] bytes = StreamUtils.copyToByteArray(request.servletRequest().getInputStream());
	String requestBody = new String(bytes, StandardCharsets.UTF_8);
	LOGGER.info(requestBody);
	return next.handle(request);
})

I have used the example from the documentation: ModifyRequestBody Filter

bsgrd avatar Feb 15 '24 12:02 bsgrd

@bsgrd try pass requestBody. next.handle(requestBody);

NiiazKhan avatar Feb 18 '24 19:02 NiiazKhan

I'm unable to reproduce this using this initializr setup

If you'd like us to spend some time investigating, please take the time to provide a complete, minimal, verifiable sample (something that we can unzip attached to this issue or git clone, build, and deploy) that reproduces the problem.

spencergibb avatar Mar 11 '24 19:03 spencergibb

Hi @spencergibb I created a minimal repo with my setup here boot 3.2.2 and cloud 2023.0.0 here gateway I'm gonna test with your initializer setup.

bsgrd avatar Mar 12 '24 18:03 bsgrd

I still can't reproduce with your repository. How are you making the http request?

spencergibb avatar Mar 12 '24 18:03 spencergibb

@spencergibb weird. I'm doing a simple POST request with postman and a random json body. I also just tried a curl request with same result: curl -H 'Content-Type: application/json' -d '{ "title":"foo","body":"bar", "id": 1}' -X POST http://localhost:8080

bsgrd avatar Mar 12 '24 18:03 bsgrd

BTW. I should mention that I'm using Java 21. Don't know if that makes a difference. Though i get the same error with java 17.

bsgrd avatar Mar 12 '24 18:03 bsgrd

I see, the path of the uri is not used. See #3292 and #3293

https://github.com/bsgrd/gateway/pull/1

spencergibb avatar Mar 12 '24 19:03 spencergibb

@spencergibb I'm still getting the same error with your fix. I have added a screenshot and the stacktrace.

image

stacktrace.txt

bsgrd avatar Mar 13 '24 07:03 bsgrd

Using GatewayRouterFunctions.route() was the difference. PR updated.

spencergibb avatar Mar 13 '24 22:03 spencergibb