简体   繁体   English

如何在rails中安全地保存/检索HTML标签到数据库?

[英]How to safely save/retrieve HTML tags to database in rails?

I need to safely save/retrieve HTML tags to a database in my rails app. 我需要在我的rails应用程序中安全地将HTML标记保存/检索到数据库。 Currently I save HTML without any validation like below: 目前我保存HTML没有任何验证如下:

<h2>Sample title</h2> 
<p>sample description</p>

and in the view I use <%=raw @page.desription %> . 在视图中我使用<%=raw @page.desription %> It works as expected. 它按预期工作。 But I need to know if it is safe or not? 但我需要知道它是否安全?

You can never be sure it is safe. 你永远不能确定它是安全的。 Always treat all user input as hostile. 始终将所有用户输入视为敌对。

However, if by "safe" you mean "devoid of potentially really harmful elements like <script> s and <style> s", then I present to you the Sanitization Helper . 但是,如果“安全”是指“没有像<script> s和<style> s这样的潜在真正有害的元素”,那么我就向你呈现消毒助手 You can print your HTML from the database and only allow a certain whitelist of tags. 您可以从数据库中打印HTML,并且只允许使用某些标签白名单。

<%=raw sanitize @page.description, tags: %w(h2 p strong em a), attributes: %w(id class href) %>

The above example will allow all h2 , p , strong , em and a tags, and only the id , class and href attributes on them. 上面的例子将允许所有h2pstrongema标签,以及它们上只有idclasshref属性。 Everything else will be removed. 其他一切都将被删除。

It's safe as long as it's from a trusted source, otherwise you won't know what it is they're storing exactly. 它是安全的,只要它来自可信赖的来源,否则你不会知道它们存储的确切含义。 So if you're the only person storing it, go for it. 所以,如果你是唯一一个存储它的人,那就去吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM