I am trying to learn how CSRF vulnerability works, and how authenticity tokens in Rails help us prevent it. There’s one point that I don’t quite understand and would really appreciate it if the Rails security experts in this forum would shed some light on it.
From my understanding, the main problem behind a CSRF attack is that the server application can not differentiate between a genuine request (one that came from the application by a genuine user) vs. a forged request that came from the attacker’s website.
Rails solves this problem by inserting a unique, random token inside each form on the web application. When the form is submitted from the real application by a real user, this token is sent along with it.
My question is, what prevents an attacker to do the following:
- write JavaScript code that makes a GET request to the Rails app,
- parse its HTML contents to retrieve the authenticity token, and
- use it to make a forged request, just like a valid AJAX request would, inserting the token as part of the request?
The Rails app, upon receiving the request would be fooled into thinking the request came from the user’s app since it contains the authenticity token.
Does Rails already protects against the above scenario? If yes, how? or am I missing something that would make the above scenario impossible?
Any information is really appreciated. Thank you!
(This question was prompted by this comment on my Reddit post)