从 Rails 清理 JSON 的最佳方法
RoR 3 会自动清理 ERB 模板(如果操作正确)。然而,我有一个小项目,我仅将 RoR 用于应用程序层,并使用 javascript 进行演示。因此,典型的请求是对 Rails 路由的 ajax 调用并渲染返回的 json。问题是我目前可以注入 js,创建一个标题为 的新产品,并且在下一个请求时按原样返回浏览器愉快地解释该脚本。
最好对
- 帖子中的输入进行清理吗?
- 清理服务器上的 json 响应? (覆盖 to_json?)
- 清理客户端上的 json 响应?
我很感激任何意见。
RoR 3 automagically sanitizes ERB templates (when done correctly). However, I've got a little project where I'm using RoR for the application tier only and javascript for the presentation. So, typical request is ajax call to rails route and render returned json. Issue is it is currently possible for me to inject js, create a new product with title <script>alert('hello')</script>
and this is returned as is on the next request and the browser happily interprets the script.
Is it best to
- sanitize the inputs on post?
- sanitize the json response on the server? (override to_json?)
- sanitize the json response on the client?
I appreciate any input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将数据附加到页面时,您应该在内容客户端对 HTML 实体进行编码。
问题是,您的其他产品字段是否有意包含也会被编码的链接或段落标签之类的标记?如果是这种情况,并且您打算在页面上将 json 响应的某些部分呈现为 HTML,那么您应该在创建新产品时清理您的输入,并限制 HTML您允许添加到特定子集的标签,然后清除它们的属性。有一些库可以自动执行此过程,例如 sanitize gem。
You should encode HTML entities on the content client-side as you're appending data to the page.
The question is, do your other product fields intentionally contain markup like links or paragraph tags that will also be encoded? If this is the case, and you intend to render some parts of the json response as HTML on the page, then you should be sanitizing your input at the point when new products are created, and limited the HTML tags you allow to a specific subset, and then scrubbing away their attributes. There are libraries to automate this process, like the sanitize gem.