最近在做系统防止XSS攻击功能,从网络上找到了很多方式,大多都是通过增加过滤器,对request的参数进行过滤,在通常的情况下是有效的,但是在spring mvc中却无效。
下文方法有效,但只是对输出的时候有效
-------------------------------------------------------------------------------------------------------------------------------------
在别人的博客上看到一篇解决xss注入的办法,如下文
spring mvc 做应用时,如果采用接受或者返回 json 格式的数据的时候,有可能会产生 XSS 注入, 对于XSS注入的一个常用方法,就是将接受到的数据进行 escape 处理。如果数量很少的方法,可以自己单独处理,但如果很多地方用到,最好是用公用的方法,一个简单的方法就是 扩展jackson 定制自己的 方法,对所有json 格式数据进行escape 处理.
spring mvc json 格式处理配置
<!-- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd --> <!-- Customize ObjectMapper for XSS --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> <property name="objectMapper"> <bean class="com.yihaomen.util.CustomObjectMapper" /> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
这里注意定制的 objectMapper 属性. 具体的实现类如下:
import java.io.IOException; import org.springframework.web.util.HtmlUtils; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; public class CustomObjectMapper extends ObjectMapper { private static final long serialVersionUID = -3448961813323784217L; public CustomObjectMapper() { SimpleModule module = new SimpleModule("HTML XSS Serializer", new Version(1, 0, 0, "FINAL","com.yihaomen","ep-jsonmodule")); module.addSerializer(new JsonHtmlXssSerializer(String.class)); this.registerModule(module); } class JsonHtmlXssSerializer extends JsonSerializer<String> { public JsonHtmlXssSerializer(Class<String> string) { super(); } public Class<String> handledType() { return String.class; } public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { if (value != null) { String encodedValue = HtmlUtils.htmlEscape(value.toString()); jsonGenerator.writeString(encodedValue); } } } }
在escape 数据的时候,采用了 spring 自带的工具类 org.springframework.web.util.HtmlUtils; 来处理.这样就能对所有需要接收json 格式的数据进行统一的处理了,从而避免 XSS 注入。