那在切实需要输出包含 HTML 内容比如富文本编辑器编辑的内容时,如何保证安全?
方案很简单,只需要使用文档中推荐的 sanitize helper 方法:
It is recommended that you use sanitize instead of this method(html_safe). (#sanitize)Sanitizes HTML input, stripping all tags and attributes that aren't whitelisted.
或者使用一些其他第三方的 gem 用来做过滤处理。
总结
-
不要使用双等号缩写的方式,以避免其他人(比如项目里的 Rails 新手)在不了解的情况下照着滥用;
尽可能不用 raw helper 或者 String#html_safe 方法,尽可能使用 #sanitize;
多借助工具进行自动扫描,比如 brakeman,能够快速高效检测出包括 XSS 漏洞在内的多种安全隐患。










