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.

5 thoughts on “Rails 4 CSRF Protection with Clients using APIs

  1. LastBrook says:

    I see you don’t monetize your page, don’t waste your traffic, you can earn additional
    bucks every month because you’ve got hi quality content.
    If you want to know how to make extra $$$, search for:
    Mertiso’s tips best adsense alternative

  2. JaneSmall says:

    I have checked your page and i have found some duplicate content, that’s why you don’t rank high in google, but
    there is a tool that can help you to create 100%
    unique articles, search for; Boorfe’s tips unlimited
    content

Leave a Reply

Your email address will not be published. Required fields are marked *