How to Sanitize in Rails

Kelina
2 min readSep 5, 2020

--

Rails Security
Photo by Moja Msanii on Unsplash

Cross-site scripting in application are common and makes application unresponsive if not treated right.

Preventing XSS injections in an application is necessary from a security perspective. And yeah, who wants to get bombarded with requests and pop ups that are annoying?!

Some of the common XSS attacks which needs to be handled are

<svg/onload=alert(1)><svg.onload=confirm(document.cookie) y>{{constructor.constructor('alert(1)')()}}

All of the above XSS attacks either opens an alert box or a confirm box automatically clicking yes and running the script before you even know it.

And yes, it doesn’t end easily!

So, how to prevent these XSS attacks in the application?

In Rails, it is pretty easier than we think.

The first and foremost thing we must do is sanitizing the parameters. And to do so, we need a sanitizer module which sanitizes different types of parameters.

You can see a module for just sanitizing any kind of parameters — object, array or a file. You can use them with a simple function and pass all the ActionController Parameters and sanitize them. Poof!!

Though we can get sanitize the parameters, there are some cases where we want to retain &, <, >like in timezone name.

For that, unfortunately we have to save it as permitted params and save them after sanitizing the parameters.

For rendering sanitized text, you can use sanitize_text for those where you do not have to show <> and & otherwise you can use steralize_text to render them in the views.

So now you can sanitize both parameters and views in Rails with a simple sanitizer module.

Voila!!!

--

--