Rails: How Does csrf_meta_tag Work?

Nick picture Nick · Apr 3, 2012 · Viewed 51.6k times · Source

I'm a PHP developer learning Ruby on Rails by reading Michael Hartl's tutorial. Here is a quote from the book, referring to csrf_meta_tag:

...the Rails method csrf_meta_tag [prevents] cross-site request forgery (CSRF), a type of malicious web attack. Don’t worry about the details (I don’t); just know that Rails is working hard to keep your application secure.

The thing is, I'm genuinely curious. How does inserting csrf-param and csrf-token meta tags prevent CSRF? I tried Googling, but couldn't find anything.

Answer

Frederick Cheung picture Frederick Cheung · Apr 3, 2012

csrf_meta_tag is basically fulfilling the same thing as hidden form fields but is there to give javascript requests that aren't tied to a form an easy way of getting the token.

If you use the jquery-ujs library the content of that meta tag is automatically added (as a request header) to any ajax requests made.