0

I need to calculate a value for every request body (soap requests) for this i created a filter (extending OncePerRequestFilter):

@Component
@RequiredArgsConstructor
public class AddHashFilter extends OncePerRequestFilter {

    private final RequestHash hash;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        HttpServletRequest requestToUse = request;
        if(!(request instanceof ContentCachingRequestWrapper)){
            requestToUse = new ContentCachingRequestWrapper(request);
        }

        hash.hash(IOUtils.toString(requestToUse.getInputStream(), StandardCharsets.UTF_8));

        filterChain.doFilter(requestToUse, response);
    }
}

The problem is that this somehow destroys the request - i get 400. What i tried:

  • using request.geReader -> get an exception that getReader was already called
  • omit using ContentCachingRequestWrapper -> no change

i also tried this variant to read the body (from examples i found)

@Component
@RequiredArgsConstructor
public class AddHashFilter extends OncePerRequestFilter {

    private final RequestHash hash;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {


        hash.hash(new String(StreamUtils.copyToByteArray(request.getInputStream()), StandardCharsets.UTF_8));

        filterChain.doFilter(request, response);
    }
}

The problem is same: all request are quit with 400.

But if i remove the actual work/ use of this filter (only keeping filterChain.doFilter...) it is working.

So how can i read complete body and keep it usable for everything after?

dermoritz
  • 12,519
  • 25
  • 97
  • 185

1 Answers1

1

Http request could be read only once, so if you read it in filter you can not use it again. Spring provides its own class that extends HttpServletRequest and allows reading its contents multiple times. And that resolves your problem. See this question and my answer to it: How to get request body params in spring filter?

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • as i wrote, using the ContentCachingRequestWrapper does not help. but i will check the examples again.. – dermoritz Oct 18 '22 at 15:55