Search code examples
jqueryruby-on-railscurlcsrf

How to disable CSRF for jQuery?


I am testing a remote messaging service and I "believe" I am in need of disabling CSRF in jQuery for my initial remote test to be successful.

I have disabled CSRF in the Application Controller already.

If I send the POST through the application itself, the messaging works and I get the following output in my rails server log:

Started POST "/messages" for 127.0.0.1 at 2011-05-07 10:49:29 -0400
Processing by MessagesController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxx", "message"=>{"content"=>"damn"}, "commit"=>"Send"}
SQL (0.1ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'

AREL (0.5ms) INSERT INTO "messages" ("content", "created_at", "updated_at") VALUES ('damn', '2011-05-07 14:49:29.887582', '2011-05-07 14:49:29.887582') Rendered messages/_message.html.erb (3.6ms) Rendered messages/create.js.erb (8.2ms) Completed 200 OK in 133ms (Views: 17.0ms | ActiveRecord: 0.6ms)

If I send the following POST command via cURL, I get this output:

    curl -X POST -d 'message={"content":"lololol", "commit":"Send"}' http://localhost:3000/messages

Started POST "/messages" for 127.0.0.1 at 2011-05-07 10:54:15 -0400
Processing by MessagesController#create as
Parameters: {"message"=>"{\"content\":\"lololol\", \"commit\":\"Send\"}"}
AREL (0.3ms) INSERT INTO "messages" ("content", "created_at", "updated_at") VALUES (NULL, '2011-05-07 14:54:15.934156', '2011-05-07 14:54:15.934156')
Rendered messages/_message.html.erb (0.5ms)
Rendered messages/create.js.erb (4.2ms)
Completed 200 OK in 309ms (Views: 28.1ms | ActiveRecord: 0.3ms)

I can see a blank entry on my page with a timestamp of when I run the cURL command and a record is being created in the database with everything but the content.

Is it safe to assume the reason for this is due to the CSRF in jQuery not allowing the content to get published? If so, how do I disable it? Or am POSTing it wrong with cURL? or a mixture of both?

Thank you in advance for any help.


Solution

  • Your POST is wrong. The right syntax is:

    curl -X POST -d 'message[content]=lololol&commit=Send' http://localhost:3000/messages
    

    CSRF protection wouldn't change the params. By default, when CSRF verification fails, Rails only resets the session (see the source of handle_unverified_request).