how does ASP.NET validate anti-forgery token
Asked Answered
V

3

25

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?

Valgus answered 29/10, 2014 at 0:1 Comment(1)
This explains it in .NET 5.0: levelup.gitconnected.com/…Fermanagh
T
31

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)-attacks http://www.codeproject.com/Articles/793384/ASP-NET-Anti-Forgery-Tokens-internals

Toneless answered 29/10, 2014 at 0:40 Comment(2)
Actually two tokens are generated. Not just one that is stored in two places.Echopraxia
How does this prevent an attacker from just requesting the HTML document of my site and embedding the form in their page?Digestion
E
18

A stepwise explanation that is more clear than the accepted answer imho (from https://learn.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.
Echopraxia answered 26/6, 2017 at 13:9 Comment(3)
How does "the server disallows the request"?Composure
It then does not give the requested response, but an http error code instead.Echopraxia
CSRF assumes an attacker has the user's access token. What's preventing him from requesting that HTML page, getting both anti-forgery tokens and submitting the form? It doesn't make sense.Depreciate
B
4

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 ..

Bentlee answered 14/12, 2017 at 3:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.