user3575214
user3575214

Reputation: 3897

Random CSRF token authenticity errors

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?

Upvotes: 3

Views: 989

Answers (1)

Pavling
Pavling

Reputation: 3963

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.

Upvotes: 1

Related Questions