I know rails provided CSRF protection by default from rails3. but my web application is a single page application, and all communication depend on ajax.
So, how can I get CSRF token from server before each ajax calling? or what I can do is just take off CSRF protection, right?
NOTE: we don't use any rails view to produce the web page, even the homepage, so the solution to put "<%= csrf_meta_tag %> " in .html or .erb is invalid., we use javascript framework within one page.
my env: rails3.2.3, devise2.0.4, dojo1.7.2
I would advice you to take a look at the Rails-backbone project. Specifically the backbone_rails_sync.js file.
It shows how this gem sends the CSRF-token data along with any ajax request you make to the server.
Also, here are some docs by the Django project that give you an example of how to override the default jQuery ajax() method to always send a CSRF token.
updated based on comment:
So what you where asking is how to implement CSRF when using nothing but a REST API and no views/forms are used in any way.
The answer is: don't include CSRF protection.
Cross-site request forgery is a way where another (malicious) web site reproduces or imitates a request and poses as a valid user while sending invalid data to the server.
This is only a problem when a user needs to authenticate and the authentication state is saved in the cache (to persist between page views). If a malicious web site hijacks this cache, it can submit data while pretending to be this user, without the user and server ever noticing this. This is what CSRF protection is hired to do, it injects a special string into the form that is only valid for this particular request and is unique for each other request, so even if the session is hijacked, the CSRF protection prevents any modification on the server.
In your case however, you are using HTTP API calls, and thus have to send your authentication every request through the use of the Authorization header
. This way, the credentials are never cached and can't be hijacked, so there is no need for CSRF protection.
There are other ways however to make sure your RESTful API is secure:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With