Rails 5.2:安全 form_for 以防止用户更改表单 select_tag / hidden_field 值

Rails 5.2: secure form_for to prevent user to alter form select_tag / hidden_field values

在我的表单中,我使用的是 authenticity_token: true,我想知道这是否足以防止 current_user 更改我的 select_tag 的给定选项?同样的问题适用于在我的表单中使用 hidden_field

在我的例子中有一个表单,current_user 可以在其中创建用户并将其添加到公司。 current_user 可以 select 自己的公司,例如 current_user.companies.order(:name),但是我担心 current_user 会破坏我的表格并传入不属于公司的 ID他。基本上这样current_user就可以成为外国公司的用户然后做一些下流的事情...

到目前为止,我一直在阅读 https://guides.rubyonrails.org/security.html,可能没有注意到那里的一些重要信息。我很乐意了解更多我可以采取的任何安全措施来使我的表格更安全。谢谢。

通常这种问题是在关联前要验证记录时出现的。

经典的解决方案是在提交表单后在服务器端验证它们。

例如,如果您只想创建一个与用户关联的对象,并且您将 user_id 作为 hidden_field 传递。最好直接针对当前用户创建对象,从而避免对隐藏字段进行任何操作。

而不是

Article.create(article_params) # which includes user_id provided as hidden field

current_user.articles.create(article_params) # no need of user_id

因此,对于您的情况,在创建新用户之前,您可以检查如下内容

user = User.new(params) # remove company_id from here
user.company = current_user.companies.find_by(id: params[:user_params][:company_id]) # This will set company to `nil` if the company is not associated with current user
user.save