@Html.AntiForgeryToken() invalidating previous tokens
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Describe the bug
In my Asp.Net Core website, I use @Html.AntiForgeryToken() to generate a token for my client side code and I protect my Controllers with Microsoft.AspNetCore.Mvc.AutoValidateAntiforgeryTokenAttribute. This works great with one exception. Every time I open a new page, @Html.AntiForgeryToken() is called again, which generates a token unique to the page. This new token works for the current page, but if I had another tab open, that tab ceases to work, because it is still using the old token. Each time I open a new tab, all previous tabs stop working with the generation of the new token by @Html.AntiForgeryToken().
This seems like the wrong behavior. Just because I open another tab, my existing tabs should continue to work for the lifetime of the session.
I confirmed that this behavior is different in Asp.Net Framework. Similarly, each call to @Html.AntiForgeryToken() generates a new token, but when I pass the token to System.Web.Helpers.AntiForgery.Validate(cookieValue, headerValue), all previously generated tokens continue to work, as opposed to only the most recent token working.
### Expected Behavior
I should be able to open multiple tabs of the same web page and not be blocked by the antiforgery token when I go back to my old tabs, as long as I am in the same session.
### Steps To Reproduce
1. Use @Html.AntiForgeryToken() in your cshtml file to add the hidden field to the form.
2. Protect your Controller with Microsoft.AspNetCore.Mvc.AutoValidateAntiforgeryTokenAttribute
3. Use AddAntiforgery in your application startup.
4. Ensure the header is set with the antiforgery token on all Post requests to your Controller.
5. Run your website and ensure you can make Post requests to your controller.
6. Open the same web page in a second tab and use the browser's refresh button to ensure a new page is generated with a new antiforgery token.
7. Test to see that you can successfully make Post requests to the Controller on the new tab, but you have lost the ability to do the same on the old browser tab.
### Exceptions (if any)
_No response_
### .NET Version
.Net 6
### Anything else?
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.