Ruby On Rails - Include CSRF token in HTML Form

Cros-site Security Request Forgery is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. 

Rails framework is comeup with great feature to prevent CSRF attack by mentioning method protect_from_forgery in controller. Mostly this method resides in ApplicationController, but one can migrate it in any controller.

In HTML rails has predefined helper method which generates and return CSRF-Token. This token is stored as a random string in the session, to which an attacker does not have access. This token is automatically added in as hidden field when we are using form_for helper method to generate form. But there are some cases where we have to write plain HTML to create form. 

In such cases we can even add CSRF-Token in form by defining hidden input tag with name authenticity_token. If you don't add this field in form you will possibly get warning like missing authenticity token.

Following is the example of adding that field in form :

There is one more helper call csrf_meta_tag in Rails which will return meta tag with token. i.e. form_authenticity_token. You can find the same token added in meta tag. We can even get that token via javascript and can add the token value in form.

Make sure meta tag is included in you layout file. It looks like this :     <%= csrf_meta_tag %>

Be updated with Rails Guides

Hope that helps!!!