how does ASP.NET validate anti-forgery token how does ASP.NET validate anti-forgery token asp.net asp.net

how does ASP.NET validate anti-forgery token


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:

http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-(csrf)-attackshttp://www.codeproject.com/Articles/793384/ASP-NET-Anti-Forgery-Tokens-internals


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)

  1. The client requests an HTML page that contains a form.
  2. 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.
  3. 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.)
  4. If a request does not include both tokens, the server disallows the request.


The above description is not all what is done, in case of AjaxRequest the antiforgery, specifically in get requests, will not usually send the Form with the hidden value for comparison, instead you will need to set a header value with the same content of the cookie via javascript.. the header name that you should set is by default X-XRF-Token header [related to angularjs] ... of course you will need to disable CORS or enable it for only specific domains to protect the APIs, SAMEORIGIN also need to be set to avoid clickjacking ..