dotnet/aspnetcore · error · AntiforgeryValidationException

The provided antiforgery token was meant for an authenticate

Error message

The provided antiforgery token was meant for an authenticated user, but the current request is not authenticated.

What it means

Thrown during TryValidateTokenSet when the request token was generated for an authenticated user (it carries a ClaimUid or Username) but the current request has NO authenticated identity. This is detected by IsTokenForAuthenticatedUserButCurrentUserIsNot and surfaced as AntiforgeryToken_UnauthenticatedUser. The most common root cause per the source comment (lines 200-203) is middleware ordering: UseAntiforgery runs before UseAuthentication, so the user isn't authenticated when the token is validated.

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. Fix middleware order: app.UseAuthentication() must come BEFORE app.UseAntiforgery() (and before any endpoint that validates tokens).
  2. Verify the authentication scheme is correctly configured and the auth cookie is being sent and parsed.
  3. If the session genuinely expired, redirect the user to log in and regenerate tokens rather than allowing the stale token.

Example fix

// before — wrong order
app.UseAntiforgery();
app.UseAuthentication();
app.UseAuthorization();

// after — correct order
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
Defensive patterns

Strategy: validation

Validate before calling

// In Program.cs — verify middleware order
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery(); // must be AFTER auth

Try / catch

try
{
    await _antiforgery.ValidateRequestAsync(HttpContext);
}
catch (AntiforgeryValidationException ex)
{
    if (HttpContext.User?.Identity?.IsAuthenticated != true)
        return Challenge(); // session expired
    return BadRequest(ex.Message);
}

Prevention

When it happens

Trigger: The request token embeds a username or ClaimUid (meaning it was generated while authenticated), but GetAuthenticatedIdentity(httpContext.User) returns null. Detected at line 171/179 via IsTokenForAuthenticatedUserButCurrentUserIsNot.

Common situations: UseAntiforgery() registered before UseAuthentication()/UseAuthorization() in the pipeline; the authentication middleware was removed or misconfigured; the user's session expired and they're now anonymous but still submitting an old authenticated form; authentication cookie cleared by the browser mid-session.

Understand the failure class

Related errors


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