How protect all fields against mass assignment in

2019-08-29 09:20发布

I have added this fix https://gist.github.com/2382288 for protect all fields against mass assignment in mongoid app.

in my config/initializers/mongoid.rb I have added this fix:

module Mongoid
  module MassAssignmentSecurity
    extend ActiveSupport::Concern

    included do
      attr_accessible nil
    end
  end

  module Document
    include MassAssignmentSecurity
  end
end

My question is:

this fix completely protects your application against attacks mass assignment?

Or is recommended to add attr_accessible all the attributes in each model?

4条回答
仙女界的扛把子
2楼-- · 2019-08-29 09:53

This will make all Mongoid::Documents by default accept no fields to mass-assignment. This is probably not exactly what you want, as you will not be able to @model.update(params[:model)

You'll almost certainly want to go into the document and add:

attr_accessible :first_name, :last_name
查看更多
聊天终结者
3楼-- · 2019-08-29 09:59

this fix completely protects your application against attacks mass assignment?

Yes, this will prevent mass assignment to any field and in a secure application is the correct default.

Or is recommended to add attr_accessible all the attributes in each model?

Not "or" but "and". You should use the suggested code default that forces all documents to use a white-list. Then in every document you explicitly state which fields should be accessible via mass assignment via attr_acessible statements.

查看更多
对你真心纯属浪费
4楼-- · 2019-08-29 10:09

Create an autoload file and the following:

module Mongoid
  module MassAssignmentSecurity
    extend ActiveSupport::Concern

    included do
      attr_accessible(nil)
      self.mass_assignment_sanitizer = :strict
    end
  end

  module Document
    include MassAssignmentSecurity
  end
end

Doing the above will result in proper raises as if you were working with ActiveRecord:

jordon@envygeeks:~/development/gryffindor$ rails c
Loading development environment (Rails 3.2.6)

[1] pry(main)> Page.new => #<Page _id: RANDOM_ID, _type: "Page", content: nil>
[2] pry(main)> Page.new(t: 't') => ActiveModel::MassAssignmentSecurity::Error

Without the above fix to the code you will only recieve method missing raises which is worthless because it's a general exception that does not even point your application in the right direction.

查看更多
贪生不怕死
5楼-- · 2019-08-29 10:15

I'd suggest to try out strong_parameters gem https://github.com/rails/strong_parameters http://railscasts.com/episodes/371-strong-parameters (subscription required to watch this episode)

strong_parameters will be included (and be default) in rails 4. It's already merged in rails. I'm using this gem in one of my projects and it gives great flexibility compared to attr_accessible.

查看更多
登录 后发表回答