how does ASP.NET validate anti-forgery token
I wonder how does ASP.NET check if an anti-forgery token is valid or not? Like where is ASP.NET storing those tokens? And how are they stored?
The short version is that a generated token is stored in 2 places: (a) cookie (b) hidden form value. When the form is submitted, these 2 values are compared against each other to determine if they are valid. For further reading:
A stepwise explanation that is more clear than the accepted answer imho (from https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks)
- The client requests an HTML page that contains a form.
- The server includes two tokens in the response. One token is sent as a cookie. The other is placed in a hidden form field. The tokens are generated randomly so that an adversary cannot guess the values.
- When the client submits the form, it must send both tokens back to the server. The client sends the cookie token as a cookie, and it sends the form token inside the form data. (A browser client automatically does this when the user submits the form.)
- If a request does not include both tokens, the server disallows the request.