2

I am using Rails 3 and javascript to make POST requests and therefore I need an authenticity token. However, the token Rails creates keeps including spaces, and I can't have that in my javascript URL string. Here's how it looks like in my log right now:

Started POST "/cart/update?authenticity_token=fjJJQc2gKBenzzAAqdvhprJxH2tnhYkyuZ9F+l+GFns=" for 127.0.0.1 at 2013-05-23 11:55:42 -0400
Processing by CartController#update as HTML
  Parameters: {"gift_card_amount"=>"undefined", "case_quantity"=>"", "bottle_quantity"=>"", "product_history_id"=>"1052981", "authenticity_token"=>"fjJJQc2gKBenzzAAqdvhprJxH2tnhYkyuZ9F l GFns="}
WARNING: Can't verify CSRF token authenticity

This is my HTML:

    <a href="javascript: void(0)" class="button-yellow">Add to Cart</a>
    <%= hidden_field_tag form_authenticity_token %>
    <script>
        window._token = '<%= form_authenticity_token %>';
    </script>

And my javascript:

$.post('/cart/update?authenticity_token=' + encodeURIComponent(window._token), ...

Notice I tried using encodeURIComponent, but that doesn't seem to work. However, the problem still persists and I feel like it's Rails and not javascript. How would I change the Rails token to not include spaces? gsub for + like it does in javascript?

bigpotato
  • 26,262
  • 56
  • 178
  • 334
  • 2
    The authenticity token is base64 encoded. `+` signs are valid in base64 encoding and do not represent spaces. `+` signs in URLs *do* represent spaces. So URL-encoding the token would be necessary if you need to send it as a URL parameter. To avoid this problem you could send the token as a POST parameter. However @0x0uLL's answer looks like the right way to do it. – Wodin Sep 27 '16 at 06:47

1 Answers1

1

Looks like you should actually send the csrf token in the header instead of sending it as a parameter. Also make sure you have <%= csrf_meta_tag %> in your layout. Check out this answer.

Community
  • 1
  • 1
James
  • 4,599
  • 2
  • 19
  • 27