title: How to enable CSRF in Rails 5 API mode
body: <p>I have a Rails API that's authenticated with an http-only cookie, and as such I require CSRF protection. From what I can tell, the Rails community seems to prefer storing jwt auth tokens in local storage rather than in a cookie. This avoids the need for CSRF but exposes you to XSS, which is why we chose to use cookies + csrf.</p>
  
  <p>It seems that CSRF protection is disabled by default due to the community preference for local storage. I am trying to enable it with limited success. Here is how I'm attempting to handle it:</p>
  
  <pre><code>module V1
    class ApplicationController &lt; ::ApplicationController
      include Concerns::Authentication
      include ActionController::RequestForgeryProtection
      protect_from_forgery
  
      protected
  
      def handle_unverified_request
        raise 'Invalid CSRF token'
      end
  
      after_action :set_csrf_cookie
  
      def set_csrf_cookie
        if current_user 
          cookies['X-CSRF-Token'] = form_authenticity_token
        end
      end
    end
  end
  </code></pre>
  
  <p>On the client side, I can see that the token comes back in the cookie. When I make a request, I also see that the token is present in the <code>X-CSRF-Token</code> header. All looks well so far.</p>
  
  <p>However, the <code>verified_request?</code> method returns false, so <code>handle_unverified_request</code> gets invoked. Stepping through the Rails code, I see that my token is present in <code>request.x_csrf_token</code>, but the token appears to fail verification when it's checked against the <code>session</code>. One thing I'm wondering here is if I need to enable something to get the <code>session</code> to work correctly, as I understand that session management isn't turned on be default in API mode. However, if that were the case I would sort of expect attempts to access the <code>session</code> object to blow up, and they don't, so I'm not sure.</p>
  
  <p>Have I made an error, or is there some other middleware I need to turn on? Or do I need a different approach altogether to enable CSRF with this scheme?</p>