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 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog