Fragment Caching and CSRF

What is the preferred way to handle cached forms and CSRF token? Here they suggest rewriting the JS input attribute, but I also want to cache the header.

+5
source share
2 answers

Here is an article describing the various methods: http://www.fastly.com/blog/Caching-the-Uncacheable-CSRF-security/ .

Short review:

  • Using ESI (Edge Side Includes): Render the placeholder in Rails, which you populate with the CSRF token later.
  • By including the CSRF token in the cookie and copy it into the form using javascript.
  • Get the token in a separate AJAX request and copy it into the form via javascript.

My welcome:

You need to set up a special infrastructure to use ESI, so I don’t like this solution. AJAX requests are slow and have a lot of network overhead, so I don’t like this solution either ... Therefore, I would go with a cookie solution or with the JS solution already mentioned, since these are the simplest solutions.

+4
source

it works for me. I just saved this in my application.js and everything works flawlessly.

 $.ajaxSetup({ beforeSend: function(xhr) { var csrf_value = $("meta[name='csrf-token']").attr("content"); xhr.setRequestHeader("X-CSRF-Token", csrf_value ); }, }); 
+1
source

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


All Articles