【问题标题】:do we need to explicitly sanitize strong params in rails?我们是否需要明确清理 Rails 中的强参数?
【发布时间】:2016-12-07 06:40:42
【问题描述】:
class ApplicationController < ActionController::Base
....

  def sanitize(value)
     ActionController::Base.helpers.sanitize(value.try(:strip)).gsub('&amp;', '&').gsub('&gt;', '>').gsub('&lt;', '<') if value.present?
  end

end

在资源中

class UsersController < ApplicationController
...
 def update
  if current_user.update(update_users_params)
    redirect_to root_path
  end
end

private


 def update_users_params
    params.require(:user).permit(username: sanitize(params[:user] [:username]),
                  location: sanitize(params[:user][:location]))
 end

这里的位置和用户名是用户模型属性。

不使用 sanitize 方法的实际行为:

如果我们将"Hey &lt;script type='text/javascript'&gt; alert('Hi') &lt;/script&gt;"添加到用户表单的用户名或位置输入字段中,表单提交后将按原样存储

 "Hey <script type='text/javascript'> alert('Hi') </script>"

我们需要在存储到数据库之前为脚本标签清理这些属性吗? 和

强参数是否不会从这些属性中清除脚本标签?

【问题讨论】:

    标签: javascript ruby-on-rails ruby-on-rails-4 sanitize


    【解决方案1】:

    Rails 会按原样保存输入,但在使用它时总是会对其进行转义。

    您需要显式调用 rawhtml_safe 以获取未经处理的 (html/script) 字符串。

    【讨论】:

    • 确实如此,但是如果您需要将存储的结果提供给其他平台,例如提供给 android 或 IOS 的 API 服务。
    • 这取决于你如何通过它。如果您只是将 params[:my_param_name] 传递给 API/服务,则默认情况下会对其进行转义。
    • 它不会在数据库中转义,只是当您调用/使用params 或模型属性时。
    • raw 或 html_safe 不起作用。 Rails 还带有 sanitize() 方法。即使在模型属性上,您也需要调用 sanitize() 方法。即使您在任何帮助程序或视图本身中调用它,参数也不会被转义。强参数被清理以防止任何 SQL 查询注入,所以这里不是这种情况。
    猜你喜欢
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2022-12-09
    • 2017-07-13
    • 1970-01-01
    • 2013-08-14
    相关资源
    最近更新 更多