SpringMVC 跨站指令碼攻擊防護(防止XSS攻擊)
阿新 • • 發佈:2019-01-11
SpringMVC 跨站指令碼攻擊防護(防止XSS攻擊)
- 定義一個基礎controller
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.MultipartFile;
/**
* Controller - 基類
*/
public class BaseController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(MultipartFile.class, new StringTrimmerEditor(true));
binder.registerCustomEditor(String.class, new HtmEscapeEditor(true));
}
}
HtmEscapeEditor
import org. apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.util.HtmlUtils;
/**
* HTML轉義(防止XSS攻擊)
*/
public class HtmEscapeEditor extends StringTrimmerEditor {
public HtmEscapeEditor(boolean emptyAsNull) {
super(emptyAsNull) ;
}
@Override
public void setAsText(String text) {
super.setAsText(text);
String value = (String) getValue();
if (StringUtils.isNotEmpty(value)) {
setValue(HtmlUtils.htmlEscape(value));
}
}
}
2.讓所有的controller類都繼承BaseController.
3.所有的controller所提交的資訊首先要進入BaseController.initBinder方法將輸入資訊進行轉義。
4.使用HtmlUtils.htmlUnescape()方法可以進行解碼