【问题标题】:Devise not setting current_user on Ajax post even though correct x-csrf-token is included in request header即使请求标头中包含正确的 x-csrf-token,也不要在 Ajax 帖子上设置 current_user
【发布时间】:2011-11-15 16:05:50
【问题描述】:

使用: 导轨 3.0.7 设计 1.4.5 jquery-rails 1.0.14

当通过 ajax 发布数据时,Devise 没有设置 current_donor。

我的请求标头如下所示:

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=

在关联的控制器操作中,查看会话值,我发现以下内容:

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

这将向我表明 csrf_token 与预期值匹配。然而, current_donor 仍然为零。

我已经阅读了几篇关于此的帖子,实际上,一开始,我的布局中没有 csrf_meta_tag 方法,也没有设置 csrf 令牌。

但是,情况不再如此,正在设置 csrf 令牌,但我仍然没有得到 current_donor 值。

当我发出 ajax 获取请求时,current_donor 被正确设置。

您对我应该在哪里查看的任何建议将不胜感激。

最好, 汤姆

【问题讨论】:

  • 我遇到了同样的问题。你最后解决了吗?
  • 同样的问题,Rails 4.1.6 和 Devise 3.4.1。有什么解决办法吗?

标签: jquery ruby-on-rails ajax jquery-ui devise


【解决方案1】:

我之前也遇到过同样的问题。我通过包含 csrf_token 解决了它,如下所示

$.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(){

    }
});

【讨论】:

    【解决方案2】:

    我遇到了类似的问题。我不得不改变一些其他的事情。我的 xhr 请求是使用 withCredentials 作为 true 发送的,我必须使用 Rack Cors 来允许具有特定来源的资源凭证(当凭证为 true 时这是强制性的)

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins 'my.domain.com'
        resource '/resource', headers: :any, methods: [:get], credentials: true
      end
    end
    

    那么,我的xhr:

      var ajax = new XMLHttpRequest();
      
      ajax.open("GET", url, true);
      ajax.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      ajax.withCredentials = true;
      ajax.send();
    

    说明

    我的应用程序将会话数据存储在由 _session_id cookie 标识的数据库中。我的应用程序跨子域共享 cookie,withCredentials = true,发送由第一个请求设置的 cookie。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-11
      • 2018-06-30
      • 2018-06-03
      • 2017-01-18
      • 2021-03-18
      • 2016-03-29
      • 2013-04-20
      • 2021-02-17
      相关资源
      最近更新 更多