I need to have XSS filter in my textfield, but i need to allow certain html tags for text formatting (bold, italic, etc), and i also need to allow url links like:
<p style='text-align: left;'><a href='google.com'>then with links!</a></p>
So in my entity class i added whitelist:
@SafeHtml(whitelistType = WhiteListType.RELAXED, additionalTagsWithAttributes = { @SafeHtml.Tag(name = "a", attributes = { "href" }) }) private String body;
But it still gives me the following error:
may have unsafe html content
Advertisement
Answer
You have two problems one is that style
attribute is not supported on the p
tag and second problem is that the href
attribute is missing the protocol which is required by all the WhiteListType
s. See the list below for protocols which are supported by tag and attribute for Relaxed WhiteListType
Relaxed
- tag “a”, attribute “href”, protocols {“ftp”, “http”, “https”, “mailto”}
- tag “blockquote”, attribute “cite”, protocols {“http”, “https”}
- tag “cite”, attribute “cite”, protocols {“http”, “https”}
- tag “img”, attribute “src”, protocols {“http”, “https”}
- tag “q”, attribute “cite”, protocols {“http”, “https”}
So in you case the text
<p style='text-align: left;'><a href='google.com'>then with links!</a></p>
should be changed to
<p style='text-align: left;'><a href='http://google.com'>then with links!</a></p>
and no, there is no easy way to add custom protocols 🙂
And the java code should be changed to
@SafeHtml(whitelistType = WhiteListType.RELAXED, additionalTagsWithAttributes = { @SafeHtml.Tag(name = "p", attributes = { "style" }) }) private String body;
Starting from Hibernate Validator 6 you can also provide the custom list of protocols. But sadly the @SafeHtml
also marked as deprecated, so consider writing your own validator instead.
@SafeHtml(whitelistType = SafeHtml.WhiteListType.RELAXED, additionalTagsWithAttributes = { @SafeHtml.Tag(name = "p", attributes = { "style" }, attributesWithProtocols = { @SafeHtml.Attribute(name = "a", protocols = {"http", "https"}) }) }) private String body;