Hey everyone! I've been diving into the security aspect of my site, specifically regarding CSRF tokens. I use different tokens for important changes like password updates and account settings, and I store these tokens along with their timestamps in the `$_SESSION` variable once the user logs in. For instance, I might have `$_SESSION['csrf-token1']` and `$_SESSION['csrf-token1_timestamp']`.
When a user submits a form needing a CSRF token, that token gets used, updated, and invalidated after the action. The successful form submission returns a new CSRF token, which I then update using jQuery in the current tab's hidden input fields. I also perform checks on other requests to see if the token has been valid for 30 minutes, updating them as needed.
However, I'm wondering how to refresh the CSRF tokens in any other tabs that may be open. I could keep the tokens the same for each session, but I think it's crucial to refresh or invalidate the tokens for sensitive actions.
One idea I had was to implement a background task that runs every minute to check if any token has surpassed the 30-minute mark and update or refresh them accordingly. This would ensure that the user remains authenticated during these updates. What do you guys think? Any better approaches?
3 Answers
Definitely consider generating unique token names and values for each form. This way, you can confirm the user really intended to submit that form. When a submission happens, just match the posted token’s name and value to what’s in the session. Also, keep a timestamp to track the token’s lifespan.
I’d suggest maintaining an array of CSRF tokens in your session. When a token gets used, simply remove it from the array. You can also add an expiration time to each token; when one is submitted, check its validity and unset it if it’s been used. You won’t need to worry about garbage collecting old tokens if you manage the array well.
I had a similar idea where I would keep older tokens in an array for verification. But you’re right: if two tabs are open and one token expires after a user action, the other tab won’t know it until an update happens. You’ll need to update all open tabs with the new token after a successful action.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically