Rails:如何在浏览器中显示动态html内容,而不会对其进行转义,也不会引起XSS攻击

Rails: How to show dynamic html content in the browser without escaping it and without causing XSS attack

本文关键字:转义 攻击 XSS 浏览器 内容 html 动态 显示 Rails      更新时间:2023-09-26

我想在浏览器中diplay html内容,而不必转义它。我的代码如下。

<% @mydata = "<p>paragraph</p><h1>Test</h1><script>alert('got your cookie')</script><h1>another test</h1>" %>
<%= sanitize @mydata  %>

这里我不能使用raw方法,因为raw方法会执行恶意的javascript代码,因此我使用rails sanitize方法。但问题是rails消毒方法删除了CCD_ 3行,而没有在浏览器中显示它。

我得到的输出如下

段落

测试

另一个测试


我的预期输出如下

段落

测试

警报("获取cookie")

另一个测试

有没有任何方法可以从用户输入中取消对html内容的捕获并仅转义javascript内容?

谢谢,

在rails中,您可以将标签列入白名单:

<%= sanitize @comment.body, tags: %w(strong em a), attributes: %w(href) %>
  • http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

其他方法:

选项1

require 'cgi'
CGI.escapeHTML('<h1>hi</h1><script>aeuoau</script>')
# => "&lt;h1&gt;hi&lt;/h1&gt;&lt;script&gt;aeuoau&lt;/script&gt;"
  • http://ruby-doc.org/stdlib-2.2.0/libdoc/cgi/rdoc/CGI.html

选项2

如果你正在构建一个类似博客网站的东西,在那里你会显示html代码:

  • http://coderay.rubychan.de/
  • https://github.com/rubychan/codera

选项3

如果您只想删除恶意HTML并保留常见的文本标记,如pbul。。。。

raw(simple_format('<h1>hi</h1><script>aeuoau</script>'))
# => "<p><h1>hi</h1>aeuoau</p>" 

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format

注意:simple_format将"格式化"您的代码=>将'n包装在<p></p>中,等等

其他宝石

  • https://github.com/rgrove/sanitize
  • https://github.com/flavorjones/loofah