淺談Springboot2.0防止XSS攻擊的幾種方式

在平時做項目代碼開發的時候,很容易忽視XSS攻擊的防護,網上有很多自定義全局攔截器來實現XSS過濾,其實不需要這麼麻煩,SpringBoot留有不少鉤子(擴展點),據此我們可以巧妙地實現全局的XSS過濾

防止XSS攻擊,一般有兩種做法:

轉義
使用工具類HtmlUtils實現

過濾
將敏感標簽去除
jsoup實現瞭非常強大的clean敏感標簽的功能

轉義 做法的三種實現:

轉義方法一:註冊自定義轉換器

自定義轉換器,集成PropertyEditorSupport類實現,轉換器還可以實現數據格式轉換,例如:date的轉換;

@Component
public class DateEditor extends PropertyEditorSupport {

    Pattern pattern = Pattern.compile("[^0-9]");

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StrUtil.isBlank(text)) {
            return;
        }
        text = text.trim();
        Matcher matcher = pattern.matcher(text);
        text = matcher.replaceAll("");

        int length = text.length();
        Date date;
        switch (length) {
            case 14:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHHmmss")).toDate();
                break;
            case 12:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHHmm")).toDate();
                break;
            case 10:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHH")).toDate();
                break;
            case 8:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMdd")).toDate();
                break;
            case 6:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMM")).toDate();
                break;
            case 4:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyy")).toDate();
                break;
            default:
                return;
        }
        setValue(date);
    }
}
@Component
public class StringEscapeEditor extends PropertyEditorSupport {

    public StringEscapeEditor() {
        super();
    }

    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }

    @Override
    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            String value = text;
            value = value.trim();
            setValue(value);
        }
    }
}
@Slf4j
@Component
public class CommentWebBindingInitializer extends ConfigurableWebBindingInitializer {

    private final StringEscapeEditor stringEscapeEditor;

    private final DateEditor dateEditor;

    @Autowired
    public CommentWebBindingInitializer(StringEscapeEditor stringEscapeEditor, DateEditor dateEditor) {
        this.stringEscapeEditor = stringEscapeEditor;
        this.dateEditor = dateEditor;
    }

    @Override
    public void initBinder(WebDataBinder binder) {
        log.info("init bind editor");
        super.initBinder(binder);
        // 註冊自定義的類型轉換器
        binder.registerCustomEditor(Date.class, dateEditor);
        binder.registerCustomEditor(String.class, stringEscapeEditor);
    }
}

轉義方法二:BaseController

需要XSS防護的Controller的需要繼承該BaseController

public class BaseController {
 
    @Autowired
    private StringEscapeEditor stringEscapeEditor;
 
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        binder.registerCustomEditor(String.class, stringEscapeEditor);
    }
}

轉義方法三:Converter

@Component
public class StringEscapeEditor implements Converter<String, String> {
 
    @Override
    public String convert(String s) {
        return StringUtils.isEmpty(s) ? s : HtmlUtils.htmlEscape(s);
    }
 
}
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
 
    @Autowired
    private LoginInterceptor loginInterceptor;
 
    @Autowired
    private StringEscapeEditor stringEscapeEditor;
 
    /**
     * 在參數綁定時,自定義String->String的轉換器,
     * 在轉換邏輯中對參數值進行轉義,從而達到防XSS的效果
     *
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(StringEscapeEditor);
    }
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                // 路徑不包括contextPath部分
                .excludePathPatterns("/user/login", "/user/logout", "/index/test1");
    }
 
    /**
     * 前後端分離需要解決跨域問題
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
                .allowCredentials(true).maxAge(3600);
    }
}

到此這篇關於淺談Springboot2.0防止XSS攻擊的幾種方式的文章就介紹到這瞭,更多相關Springboot防止XSS攻擊內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: