有时候我们可能要允许用户使用某些HTML标签,但是必须禁止另外一些HTML标签
我们可以在数据库存储用户输入的内容,包括允许的HTML标签,然后显示时过滤一下
让我们来一个helper方法来过滤内容,有两种方式:
1,写在application_helper.rb里
2,写在lib目录里,然后在config/environment.rb里加上[b]require_dependency 'rails_patch/text_helper'[/b]
我们推荐第二种方式,因为这样做与Rails程序松耦合
EasyHTMLWhitelists/lib/rails_patch/text_helper.rb
[code]
module ActionView
module Helpers
module TextHelper
ALLOWED_TAGS = %w(a img) unless defined?(ALLOWED_TAGS)
def whitelist(html)
# only do this if absolutely necessary
if html.index("<")
tokenizer = HTML::Tokenizer.new(html)
new_text = ""
while token = tokenizer.next
node = HTML::Node.parse(nil, 0, 0, token, false)
new_text << case node
when HTML::Tag
if ALLOWED_TAGS.include?(node.name)
node.to_s
else
node.to_s.gsub(/</, "<")
end
else
node.to_s.gsub(/</, "<")
end
end
html = new_text
end
html
end
end
end
end
[/code]
这样我们就可以在views中使用了:
[code]
<%= whitelist(@the_data) %>
[/code]
我们可以在数据库存储用户输入的内容,包括允许的HTML标签,然后显示时过滤一下
让我们来一个helper方法来过滤内容,有两种方式:
1,写在application_helper.rb里
2,写在lib目录里,然后在config/environment.rb里加上[b]require_dependency 'rails_patch/text_helper'[/b]
我们推荐第二种方式,因为这样做与Rails程序松耦合
EasyHTMLWhitelists/lib/rails_patch/text_helper.rb
[code]
module ActionView
module Helpers
module TextHelper
ALLOWED_TAGS = %w(a img) unless defined?(ALLOWED_TAGS)
def whitelist(html)
# only do this if absolutely necessary
if html.index("<")
tokenizer = HTML::Tokenizer.new(html)
new_text = ""
while token = tokenizer.next
node = HTML::Node.parse(nil, 0, 0, token, false)
new_text << case node
when HTML::Tag
if ALLOWED_TAGS.include?(node.name)
node.to_s
else
node.to_s.gsub(/</, "<")
end
else
node.to_s.gsub(/</, "<")
end
end
html = new_text
end
html
end
end
end
end
[/code]
这样我们就可以在views中使用了:
[code]
<%= whitelist(@the_data) %>
[/code]
本文介绍了一种通过编写自定义辅助方法来实现对用户输入的HTML内容进行安全过滤的方法。该方法能够有效地阻止恶意HTML标签的注入,同时允许部分安全标签通过。
640

被折叠的 条评论
为什么被折叠?



