Download CSRF token on rails using AJAX

I decided to implement my Rails site with just one page load and do the rest through AJAX. The problem is that the CSRF token that is generated in meta is not valid after being used to submit a registration or signing form. How to refresh it without reloading the page?

+4
source share
3 answers

I don’t think that rails will invalidate the CSRF meta-token after each separate request (or message or something else) (if this is not so, frameworks like backbone.js will have a difficult time :).

https://github.com/rails/rails/blob/7fb99e5743d88c04357e09960d112376428a6faa/actionpack/lib/action_controller/metal/request_forgery_protection.rb#L100

You are probably making a request BEFORE a question that you think is invalid without the correct token, and therefore the rails will delete your session, and subsequent requests will be marked as invalid even if they transmit the correct token earlier.

0
source

in every ajax request:

add to data:

authenticity_token: '<% = form_authenticity_token%>'

0
source

You can use beforeSend, as shown below, in your ajax call for put, post methods. $.ajax({ type: 'POST', beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, url: your url, data: data });

0
source

Source: https://habr.com/ru/post/1413646/


All Articles