了解何时应该使用强参数的最简单方法是了解什么是质量分配自愿性。在 Rails 3 中,您可以执行以下操作:
class CreateUsers < ActiveRecord::Migration[3.0]
def change
create_table :users do |t|
t.string :email
t.string :encrypted_password
t.boolean :admin
t.timestamps
end
end
end
class UserController < ApplicationController
def create
@user = User.new(params[:user])
if @user.save
redirect_to @user
else
render :new
end
end
end
这里我们只是将“哈希”(它实际上是一个 ActionController::Parameters 实例)直接传递到模型中。恶意用户只需请求:
POST /users?users[admin]=1
他们已经创建了一个管理员帐户。 In 2012 Egor Homakov famously exploited one such loophole in Github 提交到 Rails 存储库。
使用 cURL 或使用 Web 检查器操作表单来执行这种攻击是微不足道的。
如果我们将用户应该能够传递的属性列入白名单:
class UserController < ApplicationController
def create
@user = User.new(
params.require(:user)
.permit(:email, :password, :password_confirmation)
)
if @user.save
redirect_to @user
else
render :new
end
end
end
那么这就避免了漏洞 - 强参数实际上只是一个简单的 DSL,用于对嵌套散列结构进行切片和切块。 Rail 4 中的变化是,当您将 ActionController::Parameters 的 n 实例传递给模型时,会引发异常,除非在参数对象上调用 #permitted? 返回 true。这避免了由于程序员的懒惰或无知而发生的批量分配漏洞。
它不会以任何其他方式清理您的输入。例如,如果您不小心对待用户输入,它不会阻止 SQL 注入或远程代码执行。
如果您像这个非常人为的示例一样一一传递参数,则不需要强参数:
class UserController < ApplicationController
def create
@user = User.new do |u|
u.email = params[:user][:email]
u.password = params[:user][:password]
u.password_confirmation = params[:user][:password_confirmation]
end
if @user.save
redirect_to @user
else
render :new
end
end
end