I want to intercept the JSON sent back from a Spring MVC Rest Controller and run it through a sanitizer that ensures it's valid and HTML escapes any dodgy characters. (Possibly the OWASP JSON Sanitizer)
We use the Jackson HTTP Message converter to convert the @ResponseBody to JSON, as far as I can see once I return the object as a @ResponseBody I lose control of it.
Is there a sensible way to intercept the JSON as a String to run sanitization code on it?
I'm currently investigating three avenues:
I'm not sure if either of these will work or if there is a more sensible third option.
I know this answer may be too late, but I needed to do the same thing, so I added a serializer to the JSON mapper.
The 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) + "\"");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With