Michal
Michal

Reputation: 753

Fragment caching & CSRF

What is the prefered way to deal with cached forms and CSRF token? Here they propose a JS overwrite of input attribute, but I also want to cache the header.

Upvotes: 5

Views: 570

Answers (2)

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8132

this works for me. I just kept this in my application.js and everything work flawlessly.

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

Upvotes: 1

severin
severin

Reputation: 10268

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

A short summary:

  1. Using ESI (Edge Side Includes): render a placeholder in Rails which you fill with the CSRF token later.
  2. Including the CSRF token in a cookie and copy it into the form via javascript.
  3. Fetch the token in a separate AJAX request and copy it into the form via javascript.

My take:

You need to set up special infrastructure for using ESI, so I do not like that solution. AJAX requests are slow and a lot of network overhead, so I do not like that solution as well... So I would go with the cookie solution or with the JS solution you already mentioned, since these are the simplest solutions.

Upvotes: 6

Related Questions