Monthly Archives: October 2013

Rails 4 CSRF Protection with Clients using APIs

I was recently trying to work on a new rails site and ran into a problem with CSRF protection.  In every post/put that is submitted in Rails, a CSRF check is performed to make sure the client submitting the request has a secret token.  This is for security to prevent nasty scripts/pages from sending malicious requests from your browser.

Anyways, when you make a request from some other client, like a Java app accessing a REST service, you will get errors by default, since you do not have the secret token.  If you read about this online, many people say to just turn off the check, or to disable it for JSON requests.  This is BAD from a security perspective.

Instead, rails 4 allows you to alter the behavior when the secret isn’t sent in your request.  By default it throws an exception, but you can change it to just set the session to NULL.  This will prevent any other scripts from using your authenticated session to do bad things, and just requires you to always authenticate from your 3rd party apps.

To enable this functionality, set the following in your Application Controller:

protect_from_forgery with: :null_session

After that, just make sure your client sends credentials to authenticate for every request.