I am writing a PHP / JavaScript application. On some page loads, an AJAX request is made to obtain the data to populate the page. These AJAX requests use tokens to prevent CSRF, and are stored in PHP sessions.
Tokens are checked when a request is made, and if they are valid they then get deleted. So my set up is a token is generated in PHP, applied to the HTML body tag and then obtained and stored in a variable using JS. I only generate one token, so the same token is used for forms. Therefore a dilemma I now face is that if a page has a form and fires AJAX requests on load, the token gets deleted once it has been checked and deemed to be valid via the AJAX request. So the form will fail submission because the token its using is not valid anymore. I am seeking a suitable and sensible fix solution.
I have two ideas; first I just use a separate token for AJAX requests, which means I have two sessions dedicated to tokens. Or second, I could add some additional logic to my token class which would not delete the token on AJAX requests, so it remains valid. The second option would also allow for multiple AJAX requests using the same token too, so I could do stuff like infinite scrolling using the same token. However, I am not sure if the second solution is very secure or sensible.
So my question is, does either of my two solutions sound like a good fix or is there a better way to handle my token verification problem? And can my application become exposed to any security flaws?
Cheers