dotnet/aspnetcore · error · AntiforgeryValidationException

Validation of the provided antiforgery token failed. The coo

Error message

Validation of the provided antiforgery token failed. The cookie token and the request token were swapped.

What it means

Thrown during token validation in TryValidateTokenSet when the cookie token and request token are in the wrong roles — the cookie token lacks IsCookieToken=true or the request token has IsCookieToken=true. The two tokens are a matched pair with different internal flags, and swapping them defeats the CSRF protection model so validation fails with AntiforgeryValidationException.

Source

Thrown at src/Antiforgery/src/Internal/DefaultAntiforgery.cs:200

        // Extract cookie & request tokens
        AntiforgeryToken deserializedCookieToken;
        AntiforgeryToken deserializedRequestToken;

        DeserializeTokens(
            httpContext,
            antiforgeryTokenSet,
            out deserializedCookieToken,
            out deserializedRequestToken);

        // Validate
        if (!_tokenGenerator.TryValidateTokenSet(
            httpContext,
            deserializedCookieToken,
            deserializedRequestToken,
            out var message))
        {
            throw new AntiforgeryValidationException(message);
        }
    }

    /// <inheritdoc />
    public void SetCookieTokenAndHeader(HttpContext httpContext)
    {
        ArgumentNullException.ThrowIfNull(httpContext);

        CheckSSLConfig(httpContext);

        var antiforgeryFeature = GetCookieTokens(httpContext);
        if (!antiforgeryFeature.HaveStoredNewCookieToken && antiforgeryFeature.NewCookieToken != null)
        {
            if (antiforgeryFeature.NewCookieTokenString == null)
            {
                antiforgeryFeature.NewCookieTokenString =
                    _tokenSerializer.Serialize(antiforgeryFeature.NewCookieToken);
            }

View on GitHub (pinned to 294cab2f9b)

Solutions

  1. Do not manually split or reassign token values; use IAntiforgery.GetAndStoreTokens which returns AntiforgeryTokenSet with correctly labeled CookieToken and RequestToken fields.
  2. If writing custom token handling, ensure the CookieToken string goes only into the cookie and the RequestToken string goes only into the form field or header.
  3. Delete stale/manually-set cookies and let GetAndStoreTokens regenerate a correct pair.

Example fix

// before — tokens assigned backwards
httpContext.Response.Cookies.Append(".AspNetCore.Antiforgery", tokenSet.RequestToken);
<input name="__RequestVerificationToken" value="@tokenSet.CookieToken" />

// after — correct assignment
httpContext.Response.Cookies.Append(".AspNetCore.Antiforgery", tokenSet.CookieToken);
<input name="__RequestVerificationToken" value="@tokenSet.RequestToken" />
Defensive patterns

Strategy: validation

Try / catch

try
{
    await _antiforgery.ValidateRequestAsync(HttpContext);
}
catch (AntiforgeryValidationException ex) when (ex.Message.Contains("swapped"))
{
    return BadRequest("Token mismatch — please reload the page.");
}

Prevention

When it happens

Trigger: The client or an intermediary put the request-token value into the antiforgery cookie and the cookie-token value into the form field/header. This is detected at DefaultAntiforgeryTokenGenerator.cs:129 when (!cookieToken.IsCookieToken || requestToken.IsCookieToken).

Common situations: Manual token management code that assigns the wrong token string to the cookie vs. the form field; a custom token store or proxy that rewrites the cookie from the request body; testing utilities that hard-code tokens in the wrong slots.

Related errors


AI-assisted analysis of dotnet/aspnetcore@294cab2f9b (2026-08-06). Data as JSON: /api/errors/452b2d5b195aaf37. Report an issue: GitHub.