如何在Rails的Loofah中为白名单添加更多标签(如style标签)
在Loofah默认白名单基础上添加额外标签的方案
要给Loofah的默认白名单追加特定标签(比如style),可以通过扩展Loofah的内置白名单配置实现,分两种场景处理:
1. 单次临时修改(仅当前代码生效)
如果只需要在某一处清理逻辑中使用扩展后的白名单,不用改动全局配置,可以复制默认白名单并追加内容,再用自定义scrubber处理:
# 复制默认允许的标签集合,添加style标签 allowed_tags = Loofah::HTML5::WhiteList::ALLOWED_ELEMENTS.dup allowed_tags.add('style') # 若需要允许某些标签的特定属性(比如给div加style属性),同步扩展属性白名单 allowed_attributes = Loofah::HTML5::WhiteList::ALLOWED_ATTRIBUTES.dup allowed_attributes['div'] = (allowed_attributes['div'] || []) + ['style'] # 创建自定义的prune scrubber,使用扩展后的白名单 custom_prune_scrubber = Loofah::Scrubbers::Prune.new( allowed_elements: allowed_tags, allowed_attributes: allowed_attributes ) # 执行清理逻辑 cleaned_content = Loofah.fragment("<style>{font-family:'Roboto', Arial, sans-serif;}</style> <script>alert(h1)</script> <a href='https://google.com'>something</a> <div style='color: red;'>Later</div>") .scrub!(custom_prune_scrubber) # 替换原有的:prune scrubber .scrub!(:nofollow) .to_s
处理后style标签会被保留,script标签仍会被清理,你也可以按需添加其他标签或属性。
2. 全局配置(整个项目生效)
如果希望所有Loofah清理逻辑都自动包含新的白名单内容,可在Rails初始化文件中修改默认配置:
新建或编辑config/initializers/loofah.rb,添加以下代码:
# 给默认白名单添加style标签 Loofah::HTML5::WhiteList::ALLOWED_ELEMENTS.add('style') # 按需允许指定标签的属性,比如允许div、p标签的style属性 [ 'div', 'p', 'span' ].each do |tag| Loofah::HTML5::WhiteList::ALLOWED_ATTRIBUTES[tag] ||= [] Loofah::HTML5::WhiteList::ALLOWED_ATTRIBUTES[tag] << 'style' end
保存后重启Rails服务,原有的清理代码无需改动,会自动使用扩展后的白名单:
# 原代码保持不变,自动应用新的白名单规则 cleaned_content = Loofah.fragment("<style>{font-family:'Roboto', Arial, sans-serif;}</style> <script>alert(h1)</script> <a href='https://google.com'>something</a> <div>Later</div>") .scrub!(:prune) .scrub!(:nofollow) .to_s
注意事项
- 加入
style标签或属性时,需确保内容来源可信,避免恶意CSS带来的安全风险。 - 如需添加其他标签,直接在
allowed_tags.add()中追加即可,比如allowed_tags.add('iframe')。
内容的提问来源于stack exchange,提问作者Kunal Vashist
相关产品推荐
相关产品推荐

