通常网上搜索到的xss解决方案大多数都是增加filter,将所有带< > /等特殊字符转换,实践中这种方式确实可以防止xss攻击,但是请求数据会误伤,将原本<>字符转义后放入数据库,如果字符是大于号或者小于号的作用时,后端处理容易出现问题。
其实xss问题无非就是展示到前端的时候出现问题,所以我们可以在response的时候将数据处理,,这样就不会出现入参数据误伤问题,最直接的解决办法就是将序列化进行调整,在序列化的时候将特殊字符进行处理就可以解决xss问题
代码:
1、写个序列化,用HtmlUtils.htmlEscape进行数据处理
public class XssStringJsonSerializer extends JsonSerializer<String> {
@Override
public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(HtmlUtils.htmlEscape(s));
}
}
2、将序列化注册上
@Slf4j
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@EnableConfigurationProperties({
WebMvcProperties.class,
ResourceProperties.class,
WebProperties.class
})
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
@EnableWebMvc
@ComponentScan
public class WebAutoConfiguration implements WebMvcConfigurer, ApplicationContextAware {
@Autowired
private WebProperties webProperties;
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(String.class, new XssStringJsonSerializer());
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
List<MediaType> mediaTypes = Arrays.asList(
MediaType.APPLICATION_JSON,
MediaType.TEXT_PLAIN,
MediaType.TEXT_HTML,
MediaType.TEXT_XML,
MediaType.APPLICATION_OCTET_STREAM,
MediaType.valueOf("application/vnd.spring-boot.actuator.v3+json"));
jackson2HttpMessageConverter.setSupportedMediaTypes(mediaTypes);
converters.add(jackson2HttpMessageConverter);
}
}
通过以上操作,就可以将响应数据中的html关键字给处理掉,解决前端的xss问题