cn.twelvet.xss.core.FormXssClean Maven / Gradle / Ivy
package cn.twelvet.xss.core;
import cn.hutool.core.util.StrUtil;
import cn.twelvet.xss.config.XssProperties;
import cn.twelvet.xss.utils.XssUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import java.beans.PropertyEditorSupport;
/**
* Form xss 清理器
*
* @author twelvet
*/
@ControllerAdvice
@ConditionalOnProperty(prefix = XssProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class FormXssClean {
private final XssProperties properties;
private final XssCleaner xssCleaner;
/**
* @param properties XssProperties
* @param xssCleaner XssCleaner
*/
public FormXssClean(XssProperties properties, XssCleaner xssCleaner) {
this.properties = properties;
this.xssCleaner = xssCleaner;
}
/**
* 处理绑定数据
* @param binder WebDataBinder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
// 处理前端传来的表单字符串
binder.registerCustomEditor(String.class, new StringPropertiesEditor(xssCleaner, properties));
}
/**
* 处理字符串
*/
public static class StringPropertiesEditor extends PropertyEditorSupport {
private final static Logger log = LoggerFactory.getLogger(StringPropertiesEditor.class);
/**
* XssCleaner
*/
private final XssCleaner xssCleaner;
/**
* XssProperties
*/
private final XssProperties properties;
/**
* @param xssCleaner XssCleaner
* @param properties XssProperties
*/
public StringPropertiesEditor(XssCleaner xssCleaner, XssProperties properties) {
this.xssCleaner = xssCleaner;
this.properties = properties;
}
@Override
public String getAsText() {
Object value = getValue();
return value != null ? value.toString() : StrUtil.EMPTY;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null) {
setValue(null);
}
else if (XssHolder.isEnabled()) {
String value = xssCleaner.clean(XssUtil.trim(text, properties.isTrimText()));
setValue(value);
log.debug("Request parameter value:{} cleaned up by twelvet, current value is:{}.", text, value);
}
else {
setValue(XssUtil.trim(text, properties.isTrimText()));
}
}
}
}