Rails, Devise authentication, CSRF issue

前端 未结 10 1145
不思量自难忘°
不思量自难忘° 2020-11-28 20:52

I\'m doing a singe-page application using Rails. When signing in and out Devise controllers are invoked using ajax. The problem I\'m getting is that when I 1) sign in 2) sig

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 21:43

    My situation was even simpler. In my case, all I wanted to do was this: if a person is sitting on a screen with a form, and their session times out (Devise timeoutable session timeout), normally if they hit Submit at that point, Devise would bounce them back to the login screen. Well, I didn't want that, because they lose all their form data. I use JavaScript to catch the form submit, Ajax call a controller which determines if the user is no longer signed in, and if that's the case I put up a form where they retype their password, and I reauthenticate them (bypass_sign_in in a controller) using an Ajax call. Then the original form submit is allowed to continue.

    Was working perfectly until I added protect_from_forgery.

    So, thanks to the above answers all I needed really was in my controller where I sign the user back in (the bypass_sign_in) I just set an instance variable to the new CSRF token:

    @new_csrf_token = form_authenticity_token
    

    and then in the .js.erb that was rendered (since again, this was an XHR call):

    $('meta[name="csrf-token"]').attr('content', '<%= @new_csrf_token %>');
    $('input[type="hidden"][name="authenticity_token"]').val('<%= @new_csrf_token %>');
    

    Voila. My form page, which was not refreshed and therefore was stuck with the old token, now has the new token from the new session I got from signing in my user.

提交回复
热议问题