Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How to add CSRF Protection to forms created in javascript?

I'm using backbone.js and it works great. but the forms I'm creating as a javascript template lacks the rails csrf protection token. How do I add it to templates I'm creating in javascript?

like image 212
CamelCamelCamel Avatar asked Dec 14 '11 11:12

CamelCamelCamel


People also ask

Does every form need CSRF token?

No, you just need to generate a token on a per-session basis.

Where do I put CSRF token?

For additional safety, the field containing the CSRF token should be placed as early as possible within the HTML document, ideally before any non-hidden input fields and before any locations where user-controllable data is embedded within the HTML.

What is CSRF token in Javascript?

Cross-Site Request Forgery (CSRF, sometimes pronounced “sea-surf”), also known as one-click attack or session riding is a type of malicious attack on a web app or website. In these types of attacks, the attacker performs malicious requests on behalf of the victim.

What is CSRF How does Rails protect against it?

Briefly, Cross-Site Request Forgery (CSRF) is an attack that allows a malicious user to spoof legitimate requests to your server, masquerading as an authenticated user. Rails protects against this kind of attack by generating unique tokens and validating their authenticity with each submission.


1 Answers

Best way I solved this, inside the form:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %> 

Update:

It looks like the form_authenticity_token is private for controllers in the newer rails versions.

If that's the case for you, what I suggest is: declare a variable in a controller like: @form_token = form_authenticity_token and use it in the view you are looking for.

like image 58
lucianosousa Avatar answered Sep 20 '22 09:09

lucianosousa