Search code examples
ruby-on-railsajaxcsrf

Why does rails not verify XHR requests for CSRF?


In: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html

Which determines cross site request forgery validation. The following function:

  def non_xhr_javascript_response?
    content_type =~ %r(\Atext/javascript) && !request.xhr?
  end

Ends up meaning no XHR requests are validated for CSRF even if the token is invalid?

Why is this? Do XHR requests mean that CRSF doesn't need to be validated with Auth Token?


Solution

  • That isn't correct. Rails checks the CSRF token for all non get/head posts, whether they are ajax or not.

    In addition, since rails 4.1 Rails also checks for a csrf token for non xhr GET requests with javascript format. This is to prevent information being leaked when accessed in a cross domain request via JSON-P requests. For xhr the browser will have already enforced cross domain restrictions. This is where the method you have found is used: to see if a request needs this extra check.

    If you go back far enough in time, rails did use to exempt ajax requests from CSRF checks, because of the aforementioned browser imposed restrictions. However Rails only knows that a request is an ajax request because of the presence of an X-Requested-With header and it was found that this could be forged, so this was removed