Rails Gem 清理 - 如何列入白名单和删除
现在我们正在使用 sanitize gem: https://github.com/rgrove/sanitize
问题是如果您输入“hello & world
”,清理会将其保存在数据库中:
hello & world
如何将 &
列入白名单。我们希望通过清理来删除所有可能的恶意 html 和 JS/script 标签。但我们可以允许使用&符号。
有想法吗?谢谢
Right now we're using the sanitize gem: https://github.com/rgrove/sanitize
Problem is if you enter "hello & world
" sanitize is saving that in the DB as:
hello & world
How can you whitelist the &
. We want sanitize to remove all possible malicious html and JS/script tags. but we're ok allowing the ampersand.
Ideas? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Sanitize 始终会将输出内容转换为有效 html/xhtml 的 html 实体。
我可以确定的最好方法是过滤输出
Sanitize will always transform what is output into html entities for valid html/xhtml.
The best way I can determine is filter the output
请改用 strip_tags() 方法。
http://api.rubyonrails.org/classes/ActionView /Helpers/SanitizeHelper.html#method-i-sanitize
Use the strip_tags() method instead.
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize
UnixMonkey 的答案就是我们最终所做的。
其中 ESCAPE_SEQUENCES 是我们不想转义的字符数组。
UnixMonkey's answer is what we ended up doing.
Where ESCAPE_SEQUENCES was an array of the characters we didn't want escaped.
其他答案都不适合我。我为我的用例找到的最佳方法是使用内置的 Loofah gem:
它并不是完美无缺的不过,所以要非常小心:
有关指定方法的更多信息 此处。
绝对是我需要做的最有效的方法!
None of the other answers worked for me. The best approach I've found for my use case was using the built in Loofah gem:
It's not flawless though, so be incredibly careful:
More info on the specified method here.
Definitely the most efficient approach for what I needed to do!
从 Rails 4.2 开始,
#strip_tags
不会取消编码 HTML 特殊字符,否则您会得到以下结果:
如果您只想要 & 符号,我建议像 @Unixmonkey 建议的那样过滤输出,并将其保留为 <仅代码>&
As of Rails 4.2,
#strip_tags
does not unencode HTML special charsOtherwise you'd get the following:
If you only want the ampersand I'd suggest filtering the output like @Unixmonkey suggested and keep it to
&
only