Antiforgery Tokens Behind The Scenes

How antiforgery tokens work in .NET 5.0

David Klempfner
Level Up Coding
Published in
6 min readJan 12, 2021

--

Photo by Tom Winckels on Unsplash

In this article I’ll talk about how antiforgery tokens work behind the scenes by answering these questions:

  1. How does the cookie name get generated?
  2. How do the cookie and HTML form tokens get generated?
  3. 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:

  1. Convert the applicationId to a byte array storing UTF8 bytes.
  2. Take the SHA256 hash of this byte array.
  3. Base64URL encode that value, and that’s it!

--

--

I’m a software developer who is passionate about learning how things work behind the scenes.