Rails Gem sanitize - 如何将白名单&

时间:2011-11-08 19:10:00

标签: ruby-on-rails ruby-on-rails-3 gem sanitize

现在我们正在使用消毒宝石:https://github.com/rgrove/sanitize

问题是,如果您输入“hello & world”,则清理将数据保存在数据库中:

hello & world 

如何将&列入白名单。我们希望清理删除所有可能的恶意html和JS /脚本标记。但是我们可以使用&符号。

想法?感谢

5 个答案:

答案 0 :(得分:4)

答案 1 :(得分:3)

Sanitize将始终将输出内容转换为有效html / xhtml的html实体。

我可以确定的最佳方法是过滤输出

Sanitize.fragment("hello & world").gsub('&','&') #=> "Hello & world"

答案 2 :(得分:1)

UnixMonkey的回答是我们最终做的。

def remove_markup(html_str)
    marked_up = Sanitize.clean html_str

    ESCAPE_SEQUENCES.each do |esc_seq, ascii_seq|
      marked_up = marked_up.gsub('&' + esc_seq + ';', ascii_seq.chr)
    end
    marked_up
  end

其中ESCAPE_SEQUENCES是我们不想转义的字符数组。

答案 3 :(得分:0)

从Rails 4.2开始,#strip_tags不会取消编码HTML特殊字符

strip_tags("fun & co")
  => "fun & co"

否则您将获得以下内容:

strip_tags("<script>")
  => "<script>"

如果您只想要&符号我建议过滤输出,如@Unixmonkey建议,并将其保留到&

strip_tags("<bold>Hello & World</bold>").gsub(/&amp;/, "&")
  => "Hello & World"

答案 4 :(得分:0)

没有其他答案对我有用。我为用例找到的最佳方法是使用内置的Loofah gem:

good = '&'
bad = "<script>alert('I am evil');</script>"
greater_than = '>' # << my use case

Loofah.fragment(good).text(encode_special_chars: false)
# => "&"
Loofah.fragment(greater_than).text(encode_special_chars: false)
# => ">"

Loofah.fragment(bad).text(encode_special_chars: false)
# => "alert('I am evil');"

# And just for clarity, without the option passed in:
Loofah.fragment(good).text
# => "&amp;"

虽然它并非完美无瑕,所以要格外小心:

really_bad = "&lt;script&gt;alert('I am evil');&lt;/script&gt;"
Loofah.fragment(really_bad).text(encode_special_chars: false)
# => "<script>alert('I am evil');</script>"

有关指定方法here的更多信息。

绝对是我需要做的最有效的方法!