【问题标题】:How to show some HTML entities on title tag using Rails如何使用 Rails 在标题标签上显示一些 HTML 实体
【发布时间】:2016-06-08 02:51:14
【问题描述】:

我正在运行 Rails 4.2.x,但遇到以下问题。

某些页面的<title> 是从用户内容生成的。所以我必须使用sanitize Rails 助手来正确清理它。

但是如果用户写了“A&B”之类的东西,浏览器中显示的标题是A & B,这是错误的。

使用 Rails 转义 <title> 标签上的用户内容的正确方法是什么?至少应该包含一些特殊字符...

【问题讨论】:

  • <%= title.html_safe %> 应该会有所帮助。并查看api.rubyonrails.org/classes/ActionView/Helpers/…
  • @devanand html_safe 将用户输入标记为安全,无论它包含什么......所以这是最不安全的方法:-)
  • 我给你阅读的链接,解释了如何让用户输入更安全!
  • @devanand 我知道如何使输入更安全,一般来说,sanitize 在我们在 HTML 中间注入用户输入时效果很好。但是在这种情况下,<title> 标签对 HTML 实体很敏感,所以我不希望其中一些被转义。
  • 这就是我想说的。在这种情况下使用strip_tags。还是我误会了?

标签: ruby-on-rails xss ruby-on-rails-4.2 sanitize


【解决方案1】:

我们可以使用CGi 还有

title =  "A & B"
=> "A & B"
string = CGI.escapeHTML(title)
=> "A & B" 
string = CGI.unescapeHTML(title)
=> "A & B"

Rails 提供了如此多的逃生选择

参考这些链接:

raw vs. html_safe vs. h to unescape html

How to HTML encode/escape a string? Is there a built-in?

如果你想删除标签,你可以使用SanitizeHelper

另一种选择:WhiteListSanitizer

white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
white_list_sanitizer.sanitize(s, tags: %w())
white_list_sanitizer.sanitize(s, tags: %w(table tr td), attributes: %w(id class style))

你也可以使用Rails::Html::TargetScrubber

【讨论】:

  • CGI.unescapeHTML("<script>alert('Hello');</script>") 返回<script>alert('hello')</script>,不是很安全:-)
  • 你要删除html标签还是脚本标签
  • 我想清理用户输入,以免被 XSS 攻击
  • 是的,这就是我在问题中所描述的。它非常适合在 html 中间注入用户内容,但由于它会转义 html 实体,它会破坏我的 <title> 标记。
  • 试试这个 string.gsub(/]*>/, "")
【解决方案2】:

您可以通过 sanitize 和 htmlentities gem 的组合对 html 实体进行清理并将其转换为适当的字符。这在控制台中对我有用:

gem install htmlentities

那么……

c = ActionController::Base::ApplicationController.new
dirty_content = "<script>content & tags</script>"
clean_but_with_entities = c.helpers.sanitize(dirty_content)
nice_looking = HTMLEntities.new.decode(clean_but_with_entities.to_str )

您最终会得到“内容和标签”。为了让这个更容易使用,我把它放在 application_controller 中:

helper_method :sanitize_and_decode
def sanitize_and_decode(str)
  helpers.sanitize(str)
  HTMLEntities.new.decode(str.to_str)
end

(to_str 是为了解决here提到的SafeBuffer问题)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    相关资源
    最近更新 更多