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?