Rails 3 AJAX ignores authentication

Rails seems to ignore authentication tokens for AJAX requests. For example, I intentionally modified my AJAX call to verify this with an invalid token, and the requests seem to go fine.

The application has a default configuration for using session cookie storage and has a protect_from_forgery call in the ApplicationController.

Any ideas what else I could lose?

+6
jquery ajax ruby-on-rails-3 csrf
source share
1 answer

UPDATE >> I also posted this answer on my blog: http://zadasnotes.blogspot.com/2010/11/rails-3-forgery-csrf-protection-for.html [ archive.org ]

UPDATE 2 >> This has been changed in Rails 3.0.4. See the following post here: http://zadasnotes.blogspot.com/2011/02/rails-forgery-csrf-protection-for-ajax.html [ archive.org ]

After some research, I decided to delve a bit into the rails code documentation to find out.

Starting here: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html#method-i-form_authenticity_token

protect_from_forgery adds before_filter to verify_authenticity_token , which is shown below:

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 95 95: def verify_authenticity_token 96: verified_request? || raise(ActionController::InvalidAuthenticityToken) 97: end 

And Verified_request? shown here:

 # File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 104: def verified_request? 105: !protect_against_forgery? || request.forgery_whitelisted? || 106: form_authenticity_token == params[request_forgery_protection_token] 107: end 

Finally request.forgery_whitelisted? :

  # File actionpack/lib/action_dispatch/http/request.rb, line 126 126: def forgery_whitelisted? 127: get? || xhr? || content_mime_type.nil? || !content_mime_type.verify_request? 128: end 

Notification xhr? . xmlHttpRequest is whitelisted and not in the protect_from_forgery list. So it turns out that this is by design.

After further study of xmlHttpRequests, it turned out that there are restrictions on their launch in different domains, which makes it unnecessary to use csrf checking on xhr.

+8
source share

All Articles