Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise not setting current_user on Ajax post even though correct x-csrf-token is included in request header

Using: Rails 3.0.7 Devise 1.4.5 jquery-rails 1.0.14

When posting data via ajax, Devise is not setting current_donor.

My request header looks like this:

Host    localhost:3000
User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:6.0) Gecko/20100101     Firefox/6.0
Accept  */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection  keep-alive
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With    XMLHttpRequest
x-csrf-token    UFhqJrlOA1c1sAPeUTtV/ABcq5IeqkfA842ORcIWwks=

Within the associated controller action, looking at the session values, I find the following:

{"_csrf_token"=>"UFhqJrlOA1c1sAPeUTtV/ABcq5IeqkfA842ORcIWwks=", "warden.user.donor.key"=>["Donor", [485], "$2a$10$OtkItrzVhN4Ussnqy5k1Au"], "session_id"=>"e6693e22275385a58e0915538791ea49"}

This would indicate to me that the csrf_token matches the expected value. Yet, current_donor remains nil.

I have read through several of the posts on this, and indeed, at the outset, the csrf_meta_tag method was not in my layout, and the csrf token was not being set.

However, that is no longer the case, the csrf token is being set, and yet I am still getting no current_donor value.

When I make ajax get requests, current_donor is being set properly.

Any advice you have on where else I should look would be greatly appreciated.

Best, Tom

like image 952
TDH Avatar asked Sep 12 '11 20:09

TDH


1 Answers

I had the same problem before. I solved it by including csrf_token as below

$.ajax({
    type: "GET",
    url: url,
    data: params ,
    beforeSend: function(jqXHR, settings) {
        jqXHR.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
    },
    error: function(){
        alert("An error ocurred");
    },
    success: function(){

    }
});
like image 186
Shailesh Kalamkar Avatar answered Sep 21 '22 11:09

Shailesh Kalamkar