dotnet/aspnetcore · error · AntiforgeryValidationException

The antiforgery cookie token and request token do not match.

Error message

The antiforgery cookie token and request token do not match.

What it means

Thrown during TryValidateTokenSet when the SecurityToken embedded in the deserialized cookie token does not equal the SecurityToken embedded in the deserialized request token. The antiforgery system binds the two tokens together with a shared random SecurityToken so that a request token from one session cannot validate against a cookie from another; a mismatch means they are not a matched pair. Results in 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. Regenerate tokens on the client side: have the page fetch fresh tokens via GetAndStoreTokens before submitting, or reload the page so the new request token matches the new cookie.
  2. Ensure data protection keys are shared across all application instances (persist keys to Redis/SQL/Azure Blob) so tokens generated on one node validate on another.
  3. Check that the cookie isn't being dropped or rewritten by a reverse proxy or CDN; confirm the same cookie name (default .AspNetCore.Antiforgery) is used everywhere.
  4. Verify the application didn't change Cookie.Name or data-protection purpose strings between requests.

Example fix

// before — request token cached in static HTML, goes stale after cookie rotation
<input name="__RequestVerificationToken" value="@tokenSet.RequestToken" />

// after — refresh tokens on submit if they may be stale
async function getFreshToken() {
  const res = await fetch('/antiforgery/token');
  return (await res.json()).requestToken;
}
Defensive patterns

Strategy: try-catch

Validate before calling

// Client-side: refresh tokens before submitting long-lived pages
document.querySelector('form').addEventListener('submit', async (e) => {
  // optionally re-fetch tokens if the page is old
});

Try / catch

try
{
    await _antiforgery.ValidateRequestAsync(HttpContext);
}
catch (AntiforgeryValidationException ex)
{
    _logger.LogWarning("Token mismatch, likely stale pair: {Msg}", ex.Message);
    return BadRequest("Your session token has expired. Please reload and retry.");
}

Prevention

When it happens

Trigger: Detected at DefaultAntiforgeryTokenGenerator.cs:136 when !object.Equals(cookieToken.SecurityToken, requestToken.SecurityToken). Commonly happens when the request token was generated against a different cookie token than the one currently present (e.g., the cookie was refreshed/rotated but the client still sends an old request token).

Common situations: The antiforgery cookie expired and was regenerated by GetAndStoreTokens, but the client still submits a stale request token cached in the page; the user opened a form in one tab, the cookie rotated in another tab, and the old form is submitted; load-balanced environments with inconsistent data-protection keys causing tokens generated on one node to not match.

Related errors


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