【问题标题】:Which solution is the right way to sanitize URL for <img> & <a href> tag in GWT?哪种解决方案是清理 GWT 中 <img> 和 <a href> 标记的 URL 的正确方法?
【发布时间】:2014-04-03 04:41:41
【问题描述】:

我在谷歌上搜索如何在 GWT 中清理 URL 并发现太多不同的方法来做到这一点。我很困惑,我无法做出决定。

因此,假设您有一个允许用户输入 html url 的文本框,然后您可以将该 url 字符串包装在内部或标记中,然后再将其插入 DB。有一个表有一个列来存储 html 代码,如下所示:

<a href=\"...\">AA</a>
<img src=\"http://xxxx\">
//more html rows  here

所以假设用户输入http://car.com/pic.gif,然后用户点击提交按钮后,我希望它存储在myDB中,如下所示:

<img src=\"http://car.com/pic.gif\">

但用户可以输入任何内容,因此我们必须确保 url 输入是安全的。所以这里有一些选择:

-选项1:

String str="http://car.com/pic.gif";
if(!UriUtils.isSafeUri(str)){
   String safeStrURI=UriUtils.sanitizeUri("<img src="+str+"><br/>");
   storeUrl(safeStrURI);// store html string into DB
}

-选项2:

    String str="http://car.com/pic.gif";
    SafeHtmlBuilder builder = new SafeHtmlBuilder();
    builder.appendHtmlConstant("<img src=");
    builder.appendEscaped(str);
    builder.appendHtmlConstant("><br/>");
    String safeStrURI=builder.toString();
    storeUrl(safeStrURI);// store html string into DB

-选项3:

String str="http://car.com/pic.gif";
String safeStrURI="<img src="+UriUtils.fromString(str).asString()+"><br/>";
storeUrl(safeStrURI);// store html string into DB

/.....还有一些解决方案,但我不知道

我不明白为什么 Google 不只是制定 1 或 2 种方法来实现这一点,为什么有这么多方法可以做到这一点让我非常困惑

那么,哪个选项有利于解决我的问题。

或者你知道其他选择吗?

【问题讨论】:

    标签: gwt


    【解决方案1】:
    • 选项 1 已损坏。 sanitizeUri 应在与 HTML 位连接之前应用于 str。这使其或多或少等同于选项 3,以对 isSafeUri 的调用为模。

    • 选项 2 不安全,实际上会因为传递给 appendHtmlConstant 的值而失败(请参阅 javadoc

    IMO,您应该首先检查 isSafeUri,然后,为了真正安全,您应该连接值,但确保生成有效的 HTML(例如,值中的 "' 不会关闭您的属性值)。为此,您拥有SafeHtml,但它仅适用于 element 级别;如果你需要更深入(在属性级别),那么你有SafeHtmlTemplates(注意它只能在客户端代码中使用,与SafeHtmlSafeUri相反)

    interface Templates extends SafeHtmlTemplates {
      @Template("<img src=\"{0}\">")
      SafeHtml img(SafeUri uri);
    }
    
    static final Templates TEMPLATE = GWT.create(Templates.class);
    
    if (UriUtils.isSafeUri(str)) {
      String img = TEMPLATE.img(UriUtils.fromString(str)).asString();
      store(img);
    }
    

    【讨论】:

    • 非常感谢您的回答,但只是想知道。我需要在服务器级别检查“String img”吗?如果在客户端级别我们确定“String img”但是当传递到服务器时 img 以某种方式被改变了怎么办?但是我正在使用 GWTP 并且我设置了 SecurityCookie,所以我还需要在服务器级别进行检查吗?
    • 所以你的意思是“SafeHtmlTemplates”只能在客户端代码中使用?你能进一步解释一下吗?
    • 或者你认为这种方式更好,将 str="car.com/pic.gif" 存储到 1 列中,还有另一列将其标记为图像。当我们向用户展示时 myHtml=SafeHtmlUtils.fromSafeConstant(TEMPLATE.img(UriUtils.fromString(str)).asString());
    • SafeHtmlTemplates 依赖于 GWT 生成器 (GWT.create()) 的代码生成,因此它无法在 GWT 环境之外(例如服务器端)工作。在服务器端(和客户端),您应该可以使用"&lt;img src=\"" + SafeHtmlUtils.htmlEscape(UriUtils.sanitizeUri(str)) + "\"&gt;"
    • 但一般来说,是的,我认为避免存储 HTML 会更安全。
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2015-06-17
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多