现在我们正在使用sanitize gem:https://github.com/rgrove/sanitize
问题是,如果您输入了 "hello & world
" ,那么sanitize会将其保存到数据库中:
hello & world
如何将 &
加入白名单。我们想要消除所有可能的恶意HTML和JS/Script标签,但是我们允许使用这个&符号。
有什么建议吗?谢谢
现在我们正在使用sanitize gem:https://github.com/rgrove/sanitize
问题是,如果您输入了 "hello & world
" ,那么sanitize会将其保存到数据库中:
hello & world
如何将 &
加入白名单。我们想要消除所有可能的恶意HTML和JS/Script标签,但是我们允许使用这个&符号。
有什么建议吗?谢谢
Sanitize会始终将输出内容转换为HTML实体,以确保有效的HTML/XHTML。
我认为最好的方法是过滤输出内容。
Sanitize.fragment("hello & world").gsub('&','&') #=> "Hello & world"
sanitize()
和strip_tags
方法存在的问题是它们不能纠正格式不正确的标记,因此未匹配的<
字符会破坏页面布局。 strip_tags('Strip <ithese tags')#=>“Strip <ithese tags”
但这超出了问题所要求的:一种对内容进行清理的方式,同时仍允许原始的安带符号。 - UnixmonkeyUnixMonkey的回答就是我们最终采取的方案。
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是一个字符数组,包含我们不想转义的字符。
其他答案对我都没用。我发现适用于我的情况最好的方法是使用内置的Loofah宝石:
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
# => "&"
虽然它不是完美的,但你需要非常小心:
really_bad = "<script>alert('I am evil');</script>"
Loofah.fragment(really_bad).text(encode_special_chars: false)
# => "<script>alert('I am evil');</script>"
关于指定方法的更多信息在这里。
对于我需要做的事情来说,这绝对是最有效的方法!
gem dependency loofah --reverse-dependencies
会给你(其中之一):Used by rails-html-sanitizer-1.3.0 (loofah (~> 2.3))
。该Gem本身已经内置于Rails中,参见此处:"在Rails 4.2及以上版本中,该Gem将负责清理Rails应用程序中的HTML片段"。 - SRack#strip_tags
不会解码HTML特殊字符。strip_tags("fun & co")
=> "fun & co"
strip_tags("<script>")
=> "<script>"
&
。strip_tags("<bold>Hello & World</bold>").gsub(/&/, "&")
=> "Hello & World"
=> '&'
- bilash.sahaLoofah
- 它是内置的,非常完美 :) - SRack