有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java Hibernate@SafeHtml不允许url链接

我需要在文本字段中使用XSS过滤器,但我需要允许某些html标记用于文本格式(粗体、斜体等),并且我还需要允许url链接,如:

<p style='text-align: left;'><a href='google.com'>then with links!</a></p>

所以在我的实体类中,我添加了白名单:

@SafeHtml(whitelistType = WhiteListType.RELAXED,
        additionalTagsWithAttributes = { 
                @SafeHtml.Tag(name = "a", attributes = { "href" })
})
private String body;

但它仍然给了我以下错误:

may have unsafe html content

共 (1) 个答案

  1. # 1 楼答案

    您有两个问题,一个是style属性在p标记上不受支持,第二个问题是href属性缺少所有WhiteListType所需的协议。请参阅下面的列表,了解标签和属性为WhiteListType支持的协议

    放松的

    • 标签“a”,属性“href”,协议{“ftp”、“http”、“https”、“mailto”}
    • 标签“blockquote”,属性“cite”,协议{“http”,“https”}
    • 标签“cite”,属性“cite”,协议{“http”,“https”}
    • 标签“img”,属性“src”,协议{“http”,“https”}
    • 标签“q”,属性“cite”,协议{“http”,“https”}

    所以在你的情况下,文本

    <p style='text-align: left;'><a href='google.com'>then with links!</a></p>

    应该改成

    <p style='text-align: left;'><a href='http://google.com'>then with links!</a></p> 不,没有简单的方法可以添加自定义协议:)

    java代码应该改为

    @SafeHtml(whitelistType = WhiteListType.RELAXED,
        additionalTagsWithAttributes = { 
                @SafeHtml.Tag(name = "p", attributes = { "style" })
    })
    private String body;
    

    从Hibernate Validator 6开始,您还可以提供协议的自定义列表。但遗憾的是,{{CD8}}也被标记为弃权,所以请考虑编写自己的验证器。p>

    @SafeHtml(whitelistType = SafeHtml.WhiteListType.RELAXED,
        additionalTagsWithAttributes = {
                @SafeHtml.Tag(name = "p",
                        attributes = { "style" },
                        attributesWithProtocols = {
                            @SafeHtml.Attribute(name = "a", protocols = {"http", "https"})
                })
    })
    private String body;