Search code examples
rubyjqueryruby-on-rails-3.1cross-domaincross-domain-policy

Can't post a form to a different subdomain via Ajax (WARNING: Can't verify CSRF token authenticity)


I trying to send a remote form to a different subdomain (example.domain.com) from the one of the form (domain.com), but i keep getting the warn WARNING: Can't verify CSRF token authenticity in the log, and inspector in chrome tells me that the status of the request is (canceled), with the type application/x-www-form-urlencoded.

This is the form: button_to "Follow", follow_users_url(subdomain: post.user_username_slug), remote: true

When i remove the remote: true, i got the result i was hopping for. Also, when a try to use the same form in the same subdomain of the action (example.domain.com), i got the correct result.

I found a way to share the cookies in all subdomains (domain: :all in session_store.rb), but i can't found a way to share the token in Ajax requests.

I'm using Rails 3.1.3, Ruby 1.9.3 and jQuery 1.7.1.

Anyone can help me, please?

Edit:

The problem seems to related to CORS. Now i'm trying to find a minimum friction solution to make this (Asynchronous) cross subdomains requests work.


Solution

  • In your POST paramaters, include the field "authenticity_token" with the value returned by the helper *form_authenticity_token*. (It has nothing to do with cookies).

    Edit I think you're hitting up against the Same-Origin Policy, which prevents javascript from domain A from communicating with domain B (also applies to subdomains). There is an "override" for this called CORS, which the domain you are talking to must implement.

    So assuming you have control over both domain A and B, you can work around this limitation. This explains why "normal" requests work while ":remote => true" requests don't. (The CSRF token error is probably inaccurate.) Here's an article about setting up CORS in Rails (domain B, in my example).