3

I have a simple login form. In it, I put an AntiForegeryToken.

@using (Html.BeginForm("Login", "Account"))
{
    @Html.AntiForgeryToken()

    <p>
        <label>Email</label>
        <input type="text" name="Email" value="" />
    </p>

    <p>
        <label>Password</label>
        <input type="password" name="Password" value="" />
    </p>

    <input type="submit" value="Login" />
}

Next, I decide that I want an AFT available on every page so that I can execute certain AJAX calls that correspond with actions that require them from anywhere. To do this, I stick the AFT call in my layout view.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    @Html.AntiForgeryToken()
    @RenderBody()
</body>

I go to my login page. I see the "__RequestVerificationToken" cookie is set with a particular value. I examine my HTML and see that both AFTs (login form and layout page) have been rendered. That makes 3 different AFT values MVC has given me. I fill out the form and submit. I am logged in.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(FormCollection form)
{
    // etc.
}

I am also able to use AJAX to submit an AFT-requiring POST as well, using one of the other AFTs.

What is happening? I thought the AFT in the cookie and the one in the form were supposed to match. How is MVC doing this? What is it doing behind the scenes?

Jason
  • 133
  • 1
  • 1
  • 3
  • This article shows you how antiforgery tokens work behind the scenes in .NET 5.0, which should be similar in all versions of .NET. https://levelup.gitconnected.com/antiforgery-tokens-behind-the-scenes-dcddda54db8a – David Klempfner Jan 27 '21 at 10:08

1 Answers1

2

I thought the AFT in the cookie and the one in the form were supposed to match.

You were wrong! they doesn't need to be equal - However, they have some cryptographic relations with each other...

Here you can find detailed info about this feature and how it works...

Amin Saqi
  • 306
  • 3
  • 9