Ruby on Rails – Sanitize()

Sanitize is one of the most important gem, which needs to be installed to perform the sanitizing of parameters. In Ruby on Rails, the hackers can make use of passing the scripts like <script>alert(“hacking”);</script> in the parameter of any URL to hack the application. To get rid of this situation, we must do the following :-

gem install sanitize

gem install nokogiri (dependent gem of sanitize)

libxml2 package (dependent of nokogiri) – http://nokogiri.org/tutorials/installing_nokogiri.html

Now, add the following lines in your application controller to sanitize the parameters and automatically escaping the scripts to make your applications safer:-

  before_filter :input_filter

    def input_filter
        params.each do |key,value|
     # if it’s a hash, we need to check each value inside it…
      if value.is_a?(Hash)
       value.each do |hash_key,hash_value|
           params[key][hash_key] = Sanitize.clean(hash_value)
       end
       params[key].symbolize_keys!
      elsif value.is_a?(String) || value.is_a?(Integer)
       params[key] = Sanitize.clean(value)
      end
    end
    params.symbolize_keys!
  end

Advertisements

1 thought on “Ruby on Rails – Sanitize()”

Comments are closed.