Ben
Ben

Reputation: 5087

Spring: How to use @RequestBody after reading inputStream

I'm having the issue described here but it's not clear to me how to address it.

The issue is that I have an AuthenticationProvider which has to read the body of the request. When my controller method wants to use that data via @RequestMapping, however, it's empty because the Provider has already read the inputStream.

Is there a way to obtain an inputReader from Request which supports mark/reset so my provider can simply roll the stream back to it's initial state after it does the authentication? It seems crazy that the default behavior of the filter is destructive modification of the request object.

Upvotes: 1

Views: 3962

Answers (1)

Bozho
Bozho

Reputation: 597106

The Provider should be triggered only in specific cases, so it shouldn't affect your whole application. But if you need the body in the requests handled by the provider, then you still have a workaround:

  1. implement a servlet Filter
  2. wrap the request
  3. in the wrapper cache the request body, and then override the getInputStream() method to return a ByteArrayInputStream with the cached request body. That way it can be read muiltiple times.

spring's AbstractRequestLoggingFilter does something similar and has an example wrapper, you can check it.

Upvotes: 4

Related Questions