2

There is random CSRF errors on my app with ActionController::InvalidAuthenticityToken. Like, one out of 100 requests or more. Why would those errors appears randomly like this?

I got them on some regular <%= form_with %> tag, some on javascript post (but it works most of the time because I add the meta[name='csrf-token'] as X-CSRF-TOKEN every time), some on devise/registrations#create, etc...

Why would it happen sometimes and not every time?

Regards

Nicolas Maloeuvre
  • 3,069
  • 24
  • 42

1 Answers1

3

A CSRF token will expire when a Rails session expire (except for some configurations).

Here is a scenario raising this error :

If an user has a form displayed on a page, go away for a few dozen of minutes (depends of session duration), and comes back filling the form, the session (and token) may have expired. Then at submission Rails will raises InvalidAuthenticityToken error.

More about that here Rails CSRF Tokens - Do they expire?

Another scenario involves (bad) bots : a bot could submit the form without using the token.

colinux
  • 3,989
  • 2
  • 20
  • 19