Вопрос

Possible Duplicate:
WARNING: Can't verify CSRF token authenticity rails

I send a DELETE HTTP request using JQuery AJAX. The URL (/myitems/1234) differs from logout URL (/users/sign_out), but after the request I discover that user session was destroyed.

I'm using Devise authentication gem.

Here is the log:

Started DELETE "/myitems/2538" for 127.0.0.1 at 2012-06-26 19:09:49 +0400
Processing by MyItemsController#destroy as */*
  Parameters: {"id"=>"2538"}
WARNING: Can't verify CSRF token authenticity
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 6 LIMIT 1
   (0.0ms)  BEGIN
   (0.0ms)  UPDATE "users" SET "remember_token" = NULL,
            "remember_created_at" = NULL,
            "updated_at" = '2012-06-26 15:09:49.055774'
            WHERE "users"."id" = 6
   (1.0ms)  COMMIT
Completed 401 Unauthorized in 7ms

routes.rb contains a line:

resources :myitems

and nothing more concerning myitems.

Controller's code for delete:

def destroy
   puts 'delete'
end

Update

The same happens on POST request.

Это было полезно?

Решение

The problem (as hinted in the comment by @Thilo) is that your AJAX request does not contain the CSRF token. Rails' default behavior is to clear the session if the CSRF token doesn't match. This is why your session is being deleted.

Solutions:

1) Pass the CSRF token in your AJAX request. Depending on your needs, you may be able to leverage Rails' UJS code to automatically add the appropriate CSRF header(s).

2) Skip the authenticity token verification for the specific controller action, although that may have negative security implications.

I'm marking this as a community wiki so others can improve upon it, as I don't have time right now.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top