如何清理Java中的HTML代码以防止XSS攻击? [英] How to sanitize HTML code in Java to prevent XSS attacks?
问题描述
我得到html代码来自富文本编辑器(例如TinyMCE),但它可以发送恶意方式,忽略TinyMCE验证(异地提交的数据)。
有没有什么像使用PHP中的InputFilter一样简单?完美的解决方案我可以想象这样的作品(假设清洁剂被封装在HtmlSanitizer类中):
字符串unsanitized =...< ; ...> ...; //一些潜在的
// //输入
$ b //危险的HTML html HtmlSanitizer sat = new HtmlSanitizer(); // sanitizer util类创建了
字符串sanitized = sat.sanitize(unsanitized); //瞧 - 消毒是安全的...
更新 - 更简单的解决方案,效果更好!对于其他库/框架尽可能少的外部依赖性的小型util类 - 对我来说是最好的。
你可以尝试 rel =noreferrer> OWASP Java HTML Sanitizer 。使用非常简单。
PolicyFactory policy = new HtmlPolicyBuilder()
.allowElements(a)
.allowUrlProtocols( https)
.allowAttributes(href)。onElements(a)
.requireRelNofollowOnLinks()
.build();
字符串safeHTML = policy.sanitize(untrustedHTML);
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 text editor (e.g. TinyMCE) but it can be send malicious way around, ommiting TinyMCE validation ("Data submitted form off-site").
Is there anything as simple to use as InputFilter in PHP? Perfect solution I can imagine works like that (assume sanitizer is encapsulated in HtmlSanitizer class):
String unsanitized = "...<...>..."; // some potentially
// dangerous html here on input
HtmlSanitizer sat = new HtmlSanitizer(); // sanitizer util class created
String sanitized = sat.sanitize(unsanitized); // voila - sanitized is safe...
Update - the simpler solution, the better! Small util class with as little external dependencies on other libraries/frameworks as possible - would be best for me.
How about that?
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);
这篇关于如何清理Java中的HTML代码以防止XSS攻击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!