Sanitizing response JSON from Spring MVC controller using JSON Sanitizer?

I want to intercept the JSON sent back from Spring MVC's rest manager and run it through a sanitizer that ensures it is correct, and HTML avoids any dodgy characters. (Possibly OWASP JSON Sanitizer )

We use Jackson's HTML message converter to convert @ResponseBody to JSON, as far as I can see, as soon as I return the object as @ResponseBody, I lose control of it.

Is there any reasonable way to intercept JSON as String to run sanitation code?

I am currently studying three ways:

  • Writing a filter and a ResponseWrapper that sanitizes JSON before it is sent back to the client.
  • The JSON Mapper extension is in some way to provide sanitized JSON.
  • Writing an interceptor handler and using it to modify the response.

I am not sure if any of them will work, or if there is a more reasonable third option.

+4
source share
1 answer

I know this answer may be too late, but I had to do the same, so I added a serializer to the JSON card.

Web configuration:

import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.fasterxml.jackson.databind.ObjectMapper; @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters) { // the list is empty, so we just add our converter converters.add(jsonConverter()); } @Bean public HttpMessageConverter<Object> jsonConverter() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder .json() .serializerByType(String.class, new SanitizedStringSerializer()) .build(); return new MappingJackson2HttpMessageConverter(objectMapper); } } 

And the string serializer:

 import java.io.IOException; import org.apache.commons.lang3.StringEscapeUtils; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.NonTypedScalarSerializerBase; public class SanitizedStringSerializer extends NonTypedScalarSerializerBase<String> { public SanitizedStringSerializer() { super(String.class); } @Override public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { jgen.writeRawValue("\"" + StringEscapeUtils.escapeHtml4(value) + "\""); } } 
+2
source

All Articles