How to sanitize HTML code in Java to prevent XSS attacks?

前端 未结 5 1271
傲寒
傲寒 2020-12-05 00:29

I\'m looking for class/util etc. to sanitize HTML code i.e. remove dangerous tags, attributes and values to avoid XSS and similar attacks.

I get html code from rich

5条回答
  •  被撕碎了的回忆
    2020-12-05 00:53

    You can try OWASP Java HTML Sanitizer. It is very simple to use.

    PolicyFactory policy = new HtmlPolicyBuilder()
        .allowElements("a")
        .allowUrlProtocols("https")
        .allowAttributes("href").onElements("a")
        .requireRelNofollowOnLinks()
        .build();
    
    String safeHTML = policy.sanitize(untrustedHTML);
    

提交回复
热议问题