Should I have short lifetime for my CSRF token or can I have it last for the length of the session?
Asked
Active
Viewed 1.0k times
11
-
if it lasts the life of the session, then if it gets stolen, it case be abused for the life of that session... it should be a one-time-use – Marc B May 29 '15 at 21:24
-
No @MarcB. What makes a CSRF token special is that it's not a cookie and so not sent automatically on every request. Session lifespan is fine. [This answer](http://stackoverflow.com/a/30539335/721263) below got it right. – Neil Smithline May 29 '15 at 22:10
-
1Related question: [CSRF protection: do we have to generate a token for every form?](http://stackoverflow.com/q/8655817/53114) – Gumbo May 30 '15 at 05:48
1 Answers
13
A CSRF token is not an access token and does not have a lifetime like bearer tokens do. They are generated using session information.
csrf_token = HMAC(session_token, application_secret)
CSRF adds additional information to your requests that lets the server verify the requests comes from an authorized location.
It only affects requests where the authorization info is sent automatically by the browser (cookie auth or basic/digest scheme)

MvdD
- 22,082
- 8
- 65
- 93
-
1They don't have to be session-related. Could be per-request as well. – Neil McGuigan May 29 '15 at 23:59
-
1Why does the generation include session information? Why not using a completely random value? And it is authentication info and not authorization info. – Gumbo May 30 '15 at 05:50
-
Yes, keep your session ID protected. Don't expose it unnecessarily. – SilverlightFox May 30 '15 at 11:32
-
1Using your session ID as input to an HMAC calculation does not expose the ID itself. You can't get the ID from the HMAC. – MvdD May 30 '15 at 18:52
-
I know this is several years late, but I've seen applications where "sessions" are not a native part of the programming language, such as Node.js. If one wishes to use "sessions", you have to install third-party libraries. Hence, short TTL may be the only option regarding security if no session changing data is available that should be used instead of TTL. I'm no security expert, so please correct me if I'm wrong. – Advena Mar 31 '23 at 16:18