Rails 4 authentication only - both in the header and in the form of hidden input?

I'm trying to get full page caching in Rails, but I ended up in a big CSRF vulnerability - or maybe just because of my understanding of this. Currently, I have a form_authenticity_token string stored in a cookie that JS can receive and rewrite header tags with.

There are two places where I find markers in my generated HTML:

1) In the head

<meta name="csrf-token" content="[hash]">

2) Inside a hidden input element

<input type="hidden" name="authenticity_token" value="[different hash]">

As indicated, these hashes are different from each other (in development mode when caching is not enabled). Why are they different? Why can I remove the header meta tags and leave the form input alone and the request is allowed? But when I remove the form input tag and leave the headers, is the request rejected?

Effectively this means head tags are useless, no? I can rewrite the form input tag to a value in my cookie, as well as in the header tags, but since they are different from each other, I am careful what the end result can mean, especially when it comes to full page caching.

The application controller contains:

 protect_from_forgery with: :exception before_filter :csrf_cookie def csrf_cookie cookies['authenticity-token'.freeze] = { value: form_authenticity_token, expires: 1.day.from_now, secure: (Rails.env.staging? || Rails.env.production?) } end 
+6
source share
1 answer

Looking at SO on another issue led me to the answer . In short, Rails helps jQuery users by inserting the CSRF token into ajax requests automatically. He searches for it in meta tags.

Thus, having a CSRF token inside a form is useful when sending POST requests and using it in your head is useful for saving time / effort / errors with ajax requests.

It might be nice to have this in both cases, because you can make an ajax request when there is no form. If there is a form, and javascript is disabled, the presence in the header is not beneficial to anyone, because it will not be included in the POST request.

As for why they are different, I can only guess that this has something to do with the algorithm during generation ... but that neither here nor there how both tokens work.

+2
source

All Articles