Search code examples
ruby-on-railsrubyrakecsrfput

CSRF Token validation | Ruby | Rake | PUT |


I am trying to update data using a PUT web service against a particular id. So my json request is something like

{
    id: 1,
    status: 'A'
}

My web service expects a CSRF Token. So i first do a GET using the same url and passing the header parameter and value as

x-csrf-token => 'fetch'

The GET gives me a token, which i then pass in my request header for PUT, but still i get a CSRF Token validation failed.

I am doing the GET and the PUT in a RAKE task (of course using Ruby on rails).

Ruby version 2.0.0 Rails version 4.0.0

Any suggestions are welcome.

Thanks Abhishek


Solution

  • From Rails's code

      # Returns true or false if a request is verified. Checks:
      #
      # * is it a GET or HEAD request?  Gets should be safe and idempotent
      # * Does the form_authenticity_token match the given token value from the params?
      # * Does the X-CSRF-Token header match the form_authenticity_token
      def verified_request?
        !protect_against_forgery? || request.get? || request.head? ||
          form_authenticity_token == params[request_forgery_protection_token] ||
          form_authenticity_token == request.headers['X-CSRF-Token']
      end
    
      # Sets the token value for the current session.
      def form_authenticity_token
        session[:_csrf_token] ||= SecureRandom.base64(32)
      end
    

    The way I see it. If on your GET request you'll store token in session[:_csrf_token] and then pass it in your another request in params[:authenticity_token] (default) you should be fine.