3

I am getting intermittent CSRF token authenticity errors. Specifically, it occasionally happens when I submit a regular form via POST. I can get pass this error if I just go to a few other random pages before submitting the form again. This error does not always come up, it just comes up occasionally. It leads me to think that maybe the csrf meta tags being generated are not always valid.

I have already included the following statement in the header of application.html.erb

<%= csrf_meta_tags %>

I also have the following in application_controller.rb

protect_from_forgery

Is there anything else I should be doing?

user3575214
  • 3,327
  • 2
  • 14
  • 13

1 Answers1

1

If you're using the Rails helpers form_tag or form_for to generate your 'regular forms', then you will see if you inspect the HTML that an extra div is generated under the form tag, which contains a hidden field for utf8 compliancy, and an authenticity_token.

If you're writing your own forms (with <form>...</form> or %form) then you will need to manually add the authenticity token.

There's another helper called form_authenticity_token that you can use thus:

<input name="authenticity_token" type="hidden" value="<%= form_authenticity_token %>">

But I'd recommend you use the Rails form tag helpers, and avoid adding you own authenticity token fields.

Pavling
  • 3,933
  • 1
  • 22
  • 25
  • I am using simple_form to generate the forms and I can confirm that the authenticity token is being generated with the following lines:
    – user3575214 May 27 '14 at 14:22
  • 2
    The issue appears to be that the authenticity token values changes sometimes DURING the session. How can I prevent this from happening? And for some reason, this only appears to be happening in production and not in development. I am currently using Heroku to host the app. – user3575214 May 27 '14 at 14:24
  • I'm having this issue too - the browser is sending *some* CSRF token to the server, but Rails disagrees with what it should be. Very frustrating. – Vincent Woo Dec 23 '14 at 23:06
  • It would be worth checking the source of your HTML - do you have another form tag wrapping the form you're trying to submit? – Pavling Dec 24 '14 at 09:03