I am working on a Django project and have encountered an issue with CSRF tokens when rendering a page with a form.
To reproduce the issue, I added a 5-second delay when rendering the page. Here is the scenario:
I open the URL with the form in the first browser tab.
Within 5 seconds, I open the same URL in a second tab, ensuring that the first request hasn’t yet completed.
As a result, the first tab generates a csrftoken, and the second tab overrides it. However, the csrfmiddlewaretoken in the form on the first tab remains bound to the old csrftoken.
When I submit the form from the first tab, a CSRF error occurs due to the mismatch.
Could you please help to fix this issue? Thanks in advance!
I understand your point, but I don’t think it’s related. I believe the issue arises because the second request doesn’t carry the session from the first request (which hasn’t been responded to yet), and adding more workers won’t resolve it, as each request still requires time to be processed.
As I said before, everything I say is just estimates.
I’m just telling you what I think is most likely, and I’m not sure I’m giving you the right answer.
Additionally, a new csrf token is issued each time a user requests a page.
You are creating a problem for yourself by sending a new page request to a new tab, which changes the csrf token issued to you.
As you know, this cannot be considered a normal test.
If you want to reproduce a request that requires CSRF authentication from multiple users at the same time, test it in a normal way, not in an abnormal way.
Imagine a blog or article site where a user opens multiple articles in new tabs to read later. However, if the session expires, each tab will eventually be redirected to the login page.
Tabs opened in the background will remain inactive.
Have you ever seen that when you log out of an active tab, other inactive tabs are forcibly activated and log out?
Session confirmation is checked when the tab is active. It has no effect on inactive tabs.
I think the situation you are imagining is not normal.