Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails CSRF Tokens - Do they expire?

Tags:

I've noticed that if you post with an invalid CSRF token, rails/devise automatically signs you out.

I have an application that doesn't refresh the page, and users sit on the real-time page for a long time. Every now and then the user gets kicked out. I'm wondering if the CSRF token is expiring, making it invalid.

Which is why I'm trying to learn, does Rails CSRF tokens expire? Is there a time setting somewhere?

Thanks

like image 471
AnApprentice Avatar asked Oct 12 '11 18:10

AnApprentice


People also ask

Do CSRF tokens expire?

If a client posts a request and the cross-site request forgery (CSRF) token in the OData cookie store has expired, the token cannot be validated, and the client receives a 403 error.

How does CSRF token work in Rails?

Rails CSRF TokenThe server generates these tokens, links them to the user session, and stores them in the database. This token is then injected into any form presented to the client as a hidden field. When the client correctly submits the form for validation, it passes the token back to the server.

Are CSRF tokens single use?

CSRF tokens are often bound to the user's session: while the user is logged in, they keep the same CSRF token. However, there are some security advantages to changing the CSRF token more often, or even on every request.

Can CSRF tokens be reused?

edited. We recently had a pentest running and one security flaw that was reported is that CSRF-Tokens can be reused over multiple requests.


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.

like image 88
madlep Avatar answered Sep 18 '22 19:09

madlep