Forms Part 1 — Cross-Site Request Forgery
In Rails you can build forms in a lot of different ways. What does this mean? It means that you can from a hard coded form to a very abstract one.
So, the lowest level would be some raw HTML, just like:
<form action=”<%= songs_url %>” method=”POST”><input type=”text” name=”song[name”]
<input type=”submit”></form>
Now, when you hit submit you get:
ActionController::InvalidAuthenticityTokenYou may wonder why you get that. Rails, by design has a protection against a Cross-Site Request Forgery.
Ok.. what?
Let’s quote google on this one:
“Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user’s web browser to perform an unwanted action on a trusted site for which the user is currently authenticated.”
What’s the work around for that?
Get Pedro Henrique Altoé’s stories in your inbox
Join Medium for free to get updates from this writer.
If you are using raw HTML like in the first form example, you would need to have this line of code before your “Submit”:
<input name=”authenticity_token” type=”hidden” value=”token_value”>The authenticity_token Rails method prevents CSRF.
To make it simple to understand:
when you use a method that can modify content(PUT/POST/DELETE) Rails, through authenticity_token method, makes sure that the request are being made from the client’s browser. Not from a third party.
In fact, this is one of the reasons we want to avoid raw HTML in our Rails views. Whenever we let Rails generate the form for us(example below), the token is already present. We don’t need to worry.
<%= form_tag(songs_path) do %>
<%= text_field_tag ‘song[name]’ %><%= submit_tag %><% end %>
So if you inspect it, you can see that it’s there:
<input name=”authenticity_token” type=”hidden” value=”Hlg46F3uvymclxjRS8E33Y0wAU34qZJE3JhCTNaEUYmSPrjQHLT6cR7fvllapoXLHzbFSFanujFpq6eoHOOxwg==”>That way we can be sure that we are safe against CSRF.





