A fast and easy-to-configure HTML sanitizer written in Java that lets applications include HTML authored by third parties while protecting against cross-site scripting (XSS).
Follow the Getting Started guide to add the sanitizer with Maven or build it from source. The published artifact is com.googlecode.owasp-java-html-sanitizer:owasp-java-html-sanitizer.
Use the combinable prepackaged policies when they fit your needs.
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String safeHTML = policy.sanitize(untrustedHTML);
Build a policy for the elements, attributes, and URL protocols your application needs.
PolicyFactory policy = new HtmlPolicyBuilder()
.allowElements("a")
.allowUrlProtocols("https")
.allowAttributes("href").onElements("a")
.requireRelNofollowOnLinks()
.toFactory();
String safeHTML = policy.sanitize(untrustedHTML);
ElementPolicy and AttributePolicy allow advanced customization, including renaming elements, adding attributes, and applying application-specific checks. Elements such as a, font, img, input, and span must be explicitly allowed with allowWithoutAttributes() if they should survive without attributes.
Preprocessors support text insertion and large-scale structural changes before a policy is applied. Because preprocessing occurs before policy enforcement, it cannot weaken the security of the sanitized output.
HtmlChangeListener reports rejected elements and attributes so applications can monitor policy-violation trends. Only use the sanitizer's output: an input that triggers no change notifications is not necessarily safe.
Ask usage questions in GitHub Discussions and open GitHub issues for bugs or contribution proposals. To report a vulnerability, follow the repository Security Policy and the adversarial security review ground rules. Watch releases and security advisories for important updates.
Project Lead
Jim Manico is the founder of Manicode Security, where he trains developers and organizations in secure coding. He is an OWASP Distinguished Lifetime Member, a Java Champion, and the author of Iron-Clad Java. He leads the OWASP AISVS, Cheat Sheet Series, Java HTML Sanitizer, and Java Encoder projects.
Recognizing key contributors who have made significant impact on this project.