簡體   English   中英

使用JSON Sanitizer從Spring MVC Controller清除響應JSON?

[英]Sanitizing response JSON from Spring MVC Controller using JSON Sanitizer?

我想攔截從Spring MVC Rest Controller發送回的JSON,並通過消毒劑運行它,以確保其有效,並且HTML會轉義任何狡猾的字符。 (可能是OWASP JSON Sanitizer

據我所知,一旦我以@ResponseBody的形式返回對象,就失去了對它的控制,我們使用Jackson的HTTP Message轉換器將@ResponseBody轉換為JSON。

是否有一種明智的方式將JSON截取為String以便在其上運行清理代碼?

我目前正在調查三個途徑:

  1. 編寫一個Filter和ResponseWrapper,在將JSON發送回客戶端之前先對其進行凈化處理。
  2. 以某種方式擴展JSON Mapper以提供經過凈化的JSON。
  3. 編寫處理程序攔截器並使用它來修改響應。

我不確定這兩種方法是否都可以使用,或者是否有更明智的第三種選擇。

我知道這個答案可能為時已晚,但是我需要做同樣的事情,因此我向JSON映射器添加了序列化器。

Web配置:

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);
    }
}

和字符串序列化器:

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) + "\"");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM