1

I'd like to alter the content of the response in a Spring Security filter. Let's say all I want is as follows:

public class SecurityFilter extends OncePerRequestFilter {

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

        //response.getWriter().write("a" );
        PrintWriter p = new PrintWriter(response.getOutputStream());
        p.println("Hello");
        p.flush();
        p.close();
    }
}

Behind the filter a REST service resides that retrieves a List of Strings. If I use the getOutputStream() to write then I can the List of Strings on client (and not the String 'Hello'). If I use the getWriter() then I get the following error:

2017-08-10 09:10:42,900 ERROR [org.springframework.boot.web.support.ErrorPageFilter] (default task-7) Forwarding to error page from request [/worker/system/urmlprod30] due to exception [UT010006: 
Cannot call getWriter(), getOutputStream() already called]: java.lang.IllegalStateException: UT010006: Cannot call getWriter(), getOutputStream() already called

How can I modify the response content in Spring Security filter? BTW I use wildfly10 but it should work on Tomcat and Weblogic12c too. I use Spring Boot.

The relevant part from securityContext.xml:

    <security:csrf disabled="true" />
        <security:custom-filter ref="securityFilter" after="FORM_LOGIN_FILTER"/>
    </security:http>

I presume the response is already sent when I want to write my content but what can I do about that?

Any response would be highly appreciated!

Thanks, V.

-----UPDATE------ I forgot to mention that I need the response from the REST service as I want to manipulate it.

Viktor
  • 1,325
  • 2
  • 19
  • 41
  • Nice, it is working! I remember I tried this HttpServletResponseWrapper but I got the error... Anyway, thank you! – Viktor Aug 10 '17 at 09:14

1 Answers1

1

You can use HttpServletResponseWrapper as described here.

lzagkaretos
  • 2,842
  • 2
  • 16
  • 26
  • Thanks for the reply! I forgot to mention (...) that I need the response from the the REST service as I want to manipulate it. – Viktor Aug 10 '17 at 09:01
  • Please, take a look at [this](https://stackoverflow.com/questions/32829124/adding-header-in-response-in-filter) as it seems like something you can use. – lzagkaretos Aug 10 '17 at 09:05
  • HttpServletResponseWrapper is working? Then your comment was in the wrong place. Maybe we should update the answer for future reference. – lzagkaretos Aug 10 '17 at 09:21