{"record":{"id":"d16d7633d1577712","repo":"dotnet/aspnetcore","slug":"the-provided-antiforgery-token-was-meant-for-an-au","errorCode":null,"errorMessage":"The provided antiforgery token was meant for an authenticated user, but the current request is not authenticated.","messagePattern":"The provided antiforgery token was meant for an authenticated user, but the current request is not authenticated\\.","errorType":"exception","errorClass":"AntiforgeryValidationException","httpStatus":null,"severity":"error","filePath":"src/Antiforgery/src/Internal/DefaultAntiforgery.cs","lineNumber":200,"sourceCode":"\n        // Extract cookie & request tokens\n        AntiforgeryToken deserializedCookieToken;\n        AntiforgeryToken deserializedRequestToken;\n\n        DeserializeTokens(\n            httpContext,\n            antiforgeryTokenSet,\n            out deserializedCookieToken,\n            out deserializedRequestToken);\n\n        // Validate\n        if (!_tokenGenerator.TryValidateTokenSet(\n            httpContext,\n            deserializedCookieToken,\n            deserializedRequestToken,\n            out var message))\n        {\n            throw new AntiforgeryValidationException(message);\n        }\n    }\n\n    /// <inheritdoc />\n    public void SetCookieTokenAndHeader(HttpContext httpContext)\n    {\n        ArgumentNullException.ThrowIfNull(httpContext);\n\n        CheckSSLConfig(httpContext);\n\n        var antiforgeryFeature = GetCookieTokens(httpContext);\n        if (!antiforgeryFeature.HaveStoredNewCookieToken && antiforgeryFeature.NewCookieToken != null)\n        {\n            if (antiforgeryFeature.NewCookieTokenString == null)\n            {\n                antiforgeryFeature.NewCookieTokenString =\n                    _tokenSerializer.Serialize(antiforgeryFeature.NewCookieToken);\n            }","sourceCodeStart":182,"sourceCodeEnd":218,"githubUrl":"https://github.com/dotnet/aspnetcore/blob/294cab2f9b2e03af6b953820c7ab497c3c8b7ad9/src/Antiforgery/src/Internal/DefaultAntiforgery.cs#L182-L218","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Fix middleware order: app.UseAuthentication() must come BEFORE app.UseAntiforgery() (and before any endpoint that validates tokens).","Verify the authentication scheme is correctly configured and the auth cookie is being sent and parsed.","If the session genuinely expired, redirect the user to log in and regenerate tokens rather than allowing the stale token."],"exampleFix":"// before — wrong order\napp.UseAntiforgery();\napp.UseAuthentication();\napp.UseAuthorization();\n\n// after — correct order\napp.UseAuthentication();\napp.UseAuthorization();\napp.UseAntiforgery();","handlingStrategy":"validation","validationCode":"// In Program.cs — verify middleware order\napp.UseAuthentication();\napp.UseAuthorization();\napp.UseAntiforgery(); // must be AFTER auth","typeGuard":null,"tryCatchPattern":"try\n{\n    await _antiforgery.ValidateRequestAsync(HttpContext);\n}\ncatch (AntiforgeryValidationException ex)\n{\n    if (HttpContext.User?.Identity?.IsAuthenticated != true)\n        return Challenge(); // session expired\n    return BadRequest(ex.Message);\n}","preventionTips":["Always register UseAuthentication before UseAntiforgery in the pipeline.","After login/logout, redirect to a new page to get fresh tokens.","Test middleware order as part of integration tests."],"tags":["antiforgery","security","csrf","authentication","middleware-ordering"],"analyzedSha":"294cab2f9b2e03af6b953820c7ab497c3c8b7ad9","analyzedAt":"2026-08-06T20:08:02.189Z","schemaVersion":2},"datasetVersion":"2026-08-06T23:17:07.152Z"}