0
votes

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

1
Many apps use a token that expires every hour or so.ceejayoz
Need any more help with this? If so I'll update my answer.SilverlightFox

1 Answers

0
votes

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.

This one - there is no need to refresh the token every time.

There is no security advantage because the CSRF token should be secret anyway and cannot be read by an attacker (if it could you have bigger problems).

As long as your token is unique to the user session, unpredictable and refreshes upon every login (even after a "remember me" has created a new active session), then you're good to go.