问题
Is there any way to configure Jackson in Spring Boot so I can HTML escape all the values in the @RequestBody? I have tried with serializers but as far as I know they are defined to a specific class. I would need a filter which process all the values sent in the JSON and escape them with something like:
StringEscapeUtils.escapeHtml4(value)
Thanks
回答1:
How about creating an XSS filter and invoke it in RequestInterceptor
public class XSSRequestWrapper extends HttpServletRequestWrapper {
public XSSRequestWrapper(HttpServletRequest request) {
super(request);
}
/**
* Get XSS stripped parameter values
* @param parameter parameter values string to be checked
* @return xss striped encoded string
*/
@Override
public String[] getParameterValues(String parameter)
{
String[] values = super.getParameterValues(parameter);
if(values == null)
{
return new String[0];
}
int count = values.length;
String[] encodedValues = new String[count];
for(int i=0; i<count; i++)
{
encodedValues[i]= stripXSS(values[i]);
}
return encodedValues;
}
/**
* Get XSS stripped parameter
* @param parameter parameter string to be checked
* @return xss striped encoded string
*/
@Override
public String getParameter(String parameter)
{
String value = super.getParameter(parameter);
return stripXSS(value);
}
/**
* Get XSS stripped header
* @param name header string to be checked
* @return xss striped encoded string
*/
@Override
public String getHeader(String name)
{
String value = super.getHeader(name);
return stripXSS(value);
}
private String stripXSS(String value)
{
return HtmlUtils.htmlEscape(value);
}
}
XSS filter as below
@WebFilter(urlPatterns = "/*")
public class XSSFilter implements Filter {
/**
* Filter initialization
* @param filterConfig FilterConfig
*/
@Override
public void init(FilterConfig filterConfig) {
// nothing required here
}
/**
* Actual filter implementation
* @param servletRequest ServletRequest
* @param servletResponse ServletResponse
* @param filterChain FilterChain
* @throws IOException IOException
* @throws ServletException ServletException
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(new XSSRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
}
/**
* Filter destroy
*/
@Override
public void destroy() {
// nothing required here
}
}
来源:https://stackoverflow.com/questions/55731917/spring-boot-responsebody-jackson-escape-all-string-fields