I think you are wasting your time trying to implement per request tokens. D.W. explains it in this answer:
Of course, I know the argument why some people might recommend generating a new CSRF token for every request. They are thinking, if you also have a XSS vulnerability on your website, then if you use a single CSRF token per session it will be easy to use XSS to recover the CSRF token, whereas if you generate a new CSRF token per request, it will take more work to recover the CSRF token.
Personally, I don't find this a terribly compelling argument. If you have a XSS vulnerability on your site, it's still possible to recover CSRF tokens even if you generate a new CSRF token for every request, it just takes a few extra lines of malicious Javascript. Either way, if you have a XSS vulnerability on your site and you face a serious, knowledgeable attacker, it's hard to guarantee security, no matter how you generate your CSRF tokens.
That said, if you still want to do this perhaps the following approach would work:
- When a form loads, do an AJAX call with JavaScript to
getCsrfToken.php
or something like that. Make sure you have strict CORS on this one.
- On the server side, generate a random token if the session is valid, and send it back to the client.
- You may want to unvalidate all older tokens for that session. However, this will cause issues if the user has your site open in multiple tabs. On the other side, if you don't, whats the point?
I just dreamed up this solution now, so see it more as a suggestion to be evaluated than as a definitive secure answer.