-
Notifications
You must be signed in to change notification settings - Fork 31
Protector and Strong Parameters
Protector comes with Strong Parameters integration. It makes Strong Parameters aware of your security scopes: when you assign protected parameters to a restricted entity, Protector automatically permits values that are white-listed. This way security scopes extend to controllers keeping your code DRY and security rules centralised.
If you are on Rails >= 4.0, integration is already active.
For the earlier releases where you might be using Strong Parameters as a gem, you have to manually include it into the ActiveRecord:
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
To activate integration, extend it with the following code:
ActiveRecord::Base.send(:include, Protector::ActiveRecord::StrongParameters)
Use Protector.config.strong_parameters = false
to deactivate the integration. Alternatively you can use config.protector.strong_parameters
at any of the Rails configuration files.
class Foo
protect
can :create, :foo
can :update, :bar
end
end
Here's what going to happen at controller level:
Unrestricted entities do not change the behaviour. According to Strong Parameters policy the following code is raising ForbiddenAttributes
exception since foo
is not explicitly permitted.
params.inspect # => {:foo => true}
Foo.new(params)
foo
is automatically permitted so the following code is not raising any errors:
params.inspect # => {:foo => true}
Foo.restrict!(current_user).new(params)
Protector distracts creation from updating and only permits fields that are really suitable. In the next example, Strong Parameters raise exception since bar
is not allowed for creation (only for updating):
params.inspect # => {:foo => true, :bar => false}
Foo.restrict!(current_user).new(params)
Automatic permitting can be combined with the manual one. The following code is not raising any exceptions:
params.inspect # => {:foo => true, :bar => false}
Foo.restrict!(current_user).new(params.permit(:bar))