How to add ")]} ', \ n" before each Spring JSON response to prevent common vulnerability

I want to add a prefix ")]}',\n"

to all JSON responses generated by the servlet to prevent JSON vulnerability as AngularJS Suggestions . I found a way to change the content of the response . Using the base class OncePerRequestFilter

from Spring I get:

public class JsonArrayVulnerabilityPreventorFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        PrintWriter responseOut = response.getWriter();
        CharResponseWrapper responseWrapper = new CharResponseWrapper(response);
        filterChain.doFilter(request, responseWrapper);
        if (StringUtils.contains(responseWrapper.getHeader("Content-Type"), "application/json")) {
            responseOut.write(")]}',\n");
        }
        String originalServletResponse = responseWrapper.toString();
        responseOut.write(originalServletResponse);
    }
}

      

The problem is that when I presented the response wrapper, the header Content-Type

(and several others) disappeared from the response. I have confirmed that without the wrapper, the call will response.getHeaderNames()

return 14 different headers (including the content type), whereas with the wrapper there is only 9. It also breaks the character encoding because with the wrapper the header Content-Type

does not tell the browser that the content is in UTF-8. Why?


Source and idea CharResponseWrapper

here and here .

public class CharResponseWrapper extends HttpServletResponseWrapper {
    private CharArrayWriter output;

    public String toString() {
        return output.toString();
    }

    public CharResponseWrapper(HttpServletResponse response) {
        super(response);
        output = new CharArrayWriter();
    }

    public PrintWriter getWriter() {
        return new PrintWriter(output);
    }
}

      

+3


source to share


2 answers


Actually, I solved the root problem (adding a prefix )]}',\n

to each JSON response) with the following configuration.



@Configuration
@EnableWebMvc
public class WebappConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setJsonPrefix(")]}',\n");
        converters.add(converter);
    }
}

      

+1


source


When using Spring Boot , only bean can be used as shown below.

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setJsonPrefix(")]}',\n");
    return converter;

}

      



Here's an example from Spring Lemon .

+5


source







All Articles