title: How to make sure Rails API is secured from CSRF?
body: <p>I've been developing Rails app with REST API for access from mobile application.</p>
  
  <p>It works quite well. When user logs in from mobile application, he gets <code>auth_token</code> that he uses in his future requests to API. The issue is that API is also accessible from web by going to path /api/v1/... and because of this, it has to be protected from CSRF.</p>
  
  <p>I have <code>BaseApiController</code> class which inherits from <code>ApplicationController</code> that has <code>protect_from_forgery</code> "enabled". Here's example:</p>
  
  <pre><code>class Api::V1::BaseApiController &lt; ApplicationController
    # ...
  end
  
  class ApplicationController &lt; ActionController::Base
    protect_from_forgery
    # ...
  end
  </code></pre>
  
  <p>Now, when I do non-GET requests to my API, with <code>auth_token</code>, my request gets completed successfully, but in the logs I can see the famous <code>WARNING: Can't verify CSRF token authenticity</code>. If I remove <code>protect_from_forgery</code> from my <code>BaseApiController</code>, I don't get any warnings (obviously), but then my API is vulnerable to CSRF attacks (I made a simple HTML form that successfully changes the data across domains when there's no <code>protect_from_forgery</code>).</p>
  
  <p>My question is: How to assure my API stays secure, but also remove the warning when doing non-GET requests?</p>
  
  <p>Here's one of the solutions I've come up with, but it looks more like a hack and executes one extra DB query:</p>
  
  <pre><code>class Api::V1::BaseApiController &lt; ApplicationController
    # ...
    def verified_request?
      super || User.where(authentication_token: params['auth_token']).count &gt; 0
    end
  end
  </code></pre>
  
  <p>More details about the project: Rails 3.2.14, Devise, AngularJS. The project's source code can be found <a href="https://github.com/vfonic/Angular-Devise-Todolist" rel="noreferrer">here</a>.</p>