weixin_33738578 2013-10-20 04:48 采纳率: 0%
浏览 31

使用AJAX更改CSRF令牌

So I have AJAX login/logout using Devise. If I logout with AJAX, the session is reset and I'm sitting on a stale CSRF token. To work around that issue, I thought I would generate a new token in my logout server-side code, pass it back to the client, and have the client set it in the proper place. So I return JSON like so:

return render :json => {:success => true,·                                                        
                        :user_registration_path => user_registration_path,                        
                        :csrfToken => form_authenticity_token}

which I then handle in my ajax success handler, like so:

  logoutAuth: function(e, data, status, xhr) {
    console.log(data);
    console.log(status);
    console.log(data.csrfToken);
    $('.calendar').hide();
    $('.sign-out-button').hide();
    $('.right').append($('<li class="btn log-in-button"><a class="standout" href="#" data-reveal-id="login">Member Log in</a></li>'));
    $('.right').append($('<li class="btn sign-in-button"><a class="standout-primary" href="' + data.user_registration_path +·
                         '" data-reveal-id="sign-up">Member Sign up</a></li>'));
    // reset CSRF token with new token generated after sign out -- to allow AJAX with CSRF protection
    $('meta[name="csrf-token"]').attr('content', data.csrfToken);
  }

Here's the weird part: when I see what the results of calling form_authenticity_token are on the server, I get some big ass randomly generated hash. Expected. When I console.log(data.csrfToken), what that hash should have been mapped to, I get undefined. Yet other variables in my data object are accessible. Moreover, I see the token in the XHR response in my developer tools. What's up? Also, is this the preferred way of resetting an authenticity token?

  • 写回答

0条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 有偿找一份verilog语言的cnn代码带讲解
      • ¥15 关于#mysql#的问题:mysql 组内排名,取各组的销售金额前10
      • ¥15 有人用过颜色传感器吗?
      • ¥50 求一个SQL长料切短料的优化排版算法
      • ¥15 python 删除TXT文档中小写字母
      • ¥15 ValueError: not enough values to unpack (expected 2, got 0)
      • ¥15 js怎么禁止修改域名
      • ¥15 Cursor为什么在Windows11打不开
      • ¥30 java调用javacv遇到的问题
      • ¥15 如何使用matlab画出带宽100Khz,时长100ms信号的LFM形式的时频图啊