DEV Community

HOSSIEN014
HOSSIEN014

Posted on

dotnet error: Invalid anti-forgery token found

this is the error :

Microsoft.AspNetCore.Http.BadHttpRequestException: Invalid anti-forgery token found when reading parameter "string b" from the request body as form.
---> Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery cookie ".AspNetCore.Antiforgery.UwcsGqIoUSo" is not present.
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.ValidateRequestAsync(HttpContext httpContext)
at Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryMiddleware.InvokeAwaited(HttpContext context)
--- End of inner exception stack trace ---

This is a security feature designed to prevent Cross-Site Request Forgery (CSRF) attacks. Let me break it down for you:


What is Anti-Forgery Token Validation?

  • Purpose: Anti-forgery tokens are used to ensure that a form submission or POST request originates from the same application and not from a malicious third-party site.
  • How It Works:
    1. When a form is rendered, ASP.NET Core generates a hidden field containing a unique anti-forgery token.
    2. This token is also stored in a cookie.
    3. When the form is submitted, the token in the form data is validated against the token in the cookie.
    4. If the tokens don't match or are missing, the request is rejected with an error like the one you're seeing.

Why Are You Seeing This Error?

The error occurs because:

  1. Your POST endpoint is expecting a form submission with an anti-forgery token.
  2. The anti-forgery token is either missing or invalid in the request.
  3. ASP.NET Core is enforcing anti-forgery validation, but the required token is not present in the request.

How to Fix This Error

Option 1: Disable Anti-Forgery Validation (Not Recommended for Production)

If you're just testing or building a non-critical application, you can disable anti-forgery validation for the specific endpoint. However, this is not recommended for production as it exposes your application to CSRF attacks.

To disable anti-forgery validation, use the [DisableRequestSizeLimit] or [IgnoreAntiforgeryToken] attribute:

app.MapPost("/test", ([FromForm] string b) =>
{
    return Results.Ok($"Received: {b}");
}).DisableAntiforgery();
Enter fullscreen mode Exit fullscreen mode

Option 2: Add Anti-Forgery Tokens to Your Form (Recommended)

If you're building a web application with forms, you should include the anti-forgery token in your form. Here's how:

  1. Add the Anti-Forgery Token to Your Form: Use the @Html.AntiForgeryToken() helper in Razor views or manually include the token in your HTML form.

Example (Razor View):

   <form action="/test" method="post">
       <input type="text" name="b" value="Hello from form" />
       @Html.AntiForgeryToken()
       <button type="submit">Submit</button>
   </form>
Enter fullscreen mode Exit fullscreen mode

Example (Plain HTML):

   <form action="/test" method="post">
       <input type="text" name="b" value="Hello from form" />
       <input type="hidden" name="__RequestVerificationToken" value="your-anti-forgery-token-here" />
       <button type="submit">Submit</button>
   </form>
Enter fullscreen mode Exit fullscreen mode
  1. Ensure the Token is Sent in the Request: When the form is submitted, the anti-forgery token will be included in the request, and ASP.NET Core will validate it automatically.

Option 3: Use JSON Instead of Form Data

If you're building an API and don't want to deal with anti-forgery tokens, you can switch to using JSON for the request body instead of form data. Anti-forgery validation is not enforced for JSON requests.

Example:

app.MapPost("/test", (RequestModel request) =>
{
    return Results.Ok($"Received: {request.B}");
});

public class RequestModel
{
    public string B { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Request:

  • Method: POST
  • URL: /test
  • Body (JSON):
  {
      "b": "Hello from JSON"
  }
Enter fullscreen mode Exit fullscreen mode

Option 4: Configure Anti-Forgery Globally

If you want to enforce anti-forgery validation globally but exclude specific endpoints, you can configure it in Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add anti-forgery services
builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-CSRF-TOKEN"; // Custom header for anti-forgery token
});

var app = builder.Build();

// Apply anti-forgery globally
app.UseAntiforgery();

app.MapPost("/test", ([FromForm] string b) =>
{
    return Results.Ok($"Received: {b}");
});

app.Run();
Enter fullscreen mode Exit fullscreen mode

How Anti-Forgery Works in This Context

  1. Token Generation:

    • When a form is rendered, ASP.NET Core generates a unique anti-forgery token and stores it in a hidden field (__RequestVerificationToken) and a cookie.
  2. Token Validation:

    • When the form is submitted, the token in the form data is validated against the token in the cookie.
    • If the tokens match, the request is processed.
    • If the tokens don't match or are missing, the request is rejected with a BadHttpRequestException.
  3. Middleware:

    • The AntiforgeryMiddleware automatically validates the token for form submissions.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit