Sometimes can't verify CSRF token authenticity in regular web app

Viewed 689

I have a simple Rails 6 app where I use a form

<%= bootstrap_form_with(model: event, local: true, html: { multipart: true }) do |form| %>

In the generated HTML I have this is the header

<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="SOME TOKEN" />

And in the form

<input type="hidden" name="authenticity_token" value="SOME OTHER TOKEN" />

Usually all works fine, but sometimes I get an error

Can't verify CSRF token authenticity.

The log shows be that the token has been passed in the parameters and I cannot find out why the validation fails. I ma sure that there is no malicious use or anything like that.

Are there any reasons why a CSRF token loses its validity? Maybe it's only valid for a certain time?

1 Answers

CSRF protection in Rails works by storing a random value as a field in the form being submitted, and also in the user session. If the values don't match when a form is submitted, Rails rejects the form submission request.

If you're using the default cookie session store in Rails, then sessions won't expire (until the cookie does). If you're using something else (file or DB backed sessions), then yes, if those sessions expire, the form submission will fail with a CSRF error.

So if you're using cookie based sessions (the default), check the cookie expiry. If that looks OK, it's probably some other issue.

Related