I’m thinking about how to protect against CSRF in ajax-based page.
This is how I am planning do implement it, but just not sure if it’s feasable solution:
Normally you need a unique form token that is tied to user’s session, so that when a form is submitted you can compare the value of token to the one stored in SESSION
But what if you have more than one form on a page? Even more complicated - what if you don’t have actual html forms but the form is created dynamically using javascript and then submitted via ajax XHR request.
Where do you put the security token then? I was thinking to store the token in the meta tag ‘token’ then when I need to post data using javascript, the script can just read the value of meta tag ‘token’ and append it to the payload of the POST.
So when the page is created, I would add the value of token to $_SESSION[‘token’] and add the same value to
<meta name=“token” content=“23323423423”> (for example)
Then JavaScript will be able to extract this value and add to payload of any form, even if the actual form is created dynamically.
I understand your point. If I have only one unique value of $_SESSION[‘token’] then when user opens a second page or second tab, I will have to recreate the value of token, which means that the first browser window that user still has opened will have an old token which is no longer valid.
But if adding new tokens to an array then how large this array may potentially become?
I guess there should be some sort of counter that will prevent this tokens array from growing over “N” elements, like maybe 100 limit and then just start removing older elements from array.
Actually I haven’t my own CSRF implementation yet and that makes me sad, because I hate being theoretic.
But anyway.
I just thought that one token per session would be quite enough. Generated at session start. So, you were right with $_SESSION[‘token’], nothing more needed indeed.