Antiforgery Tokens Behind The Scenes
How antiforgery tokens work in .NET 5.0
In this article I’ll talk about how antiforgery tokens work behind the scenes by answering these questions:
- How does the cookie name get generated?
- How do the cookie and HTML form tokens get generated?
- How are the tokens verified?
You should already know what antiforgery tokens are, and how to use them in Asp.Net Core.
Following along
You can skip this section, however it’s much more interesting to follow along by debugging this yourself.
I won’t show all the code here, however it’s a very simple MVC application which has a form and a button to POST the form.
You can download the code from my GitHub account.
Make sure you set up VS so it opens Chrome in incognito mode so that the cookie is fresh each run.
I used these instructions in order to debug the .NET 5.0 source code.
How does the cookie name get generated?
When you make a POST request to the backend, which is set up to use antiforgery tokens, the following cookie will be sent with the request.
The cookie name is the part before the =
and the part afterwards is the value.
Let’s have a look at how those random characters are generated.
The magic happens in AntiforgeryOptionsSetup.ComputeCookieName()
.
The source code can be found here.
The C76fbftIiNo
is generated from the folder path where your solution is stored, which is stored in the applicationId
variable.
The process is:
- Convert the
applicationId
to a byte array storing UTF8 bytes. - Take the SHA256 hash of this byte array.
- Base64URL encode that value, and that’s it!