Sanitizing response JSON from Spring MVC Controller using JSON Sanitizer?

后端 未结 1 1815
天涯浪人
天涯浪人 2021-01-02 12:35

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. (Poss

相关标签:
1条回答
  • 2021-01-02 13:04

    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) + "\"");
        }
    }
    
    0 讨论(0)
提交回复
热议问题