CodexBloom - Programming Q&A Platform

Preventing CSRF Attacks in an ASP.NET Core Application with Anti-Forgery Tokens

👀 Views: 83 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
asp.net-core csrf security C#

This might be a silly question, but I'm developing an ASP.NET Core 6 application and I'm trying to implement anti-CSRF measures... I've included the anti-forgery token in my forms, but I'm working with an scenario where the token isn't being validated correctly. The token is being generated in my Razor view like this: ```csharp <form asp-controller="Home" asp-action="Submit" method="post"> @Html.AntiForgeryToken() <input type="text" name="data" required /> <button type="submit">Submit</button> </form> ``` On the server-side, I'm checking for the token using the `[ValidateAntiForgeryToken]` attribute: ```csharp [HttpPost] [ValidateAntiForgeryToken] public IActionResult Submit(string data) { // Handle submission return Ok(); } ``` However, when I submit the form, I receive the following behavior: `The anti-forgery cookie token could not be validated. The cookie token is not the same as the form token.` I have already verified that the `Antiforgery` services are added in `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // Anti-forgery services are added by default } ``` Additionally, I'm testing this in a local environment with both my frontend and backend running on the same origin. I thought this would prevent any cross-origin issues. I've also checked that cookies are being sent with the request; they are present in the request headers: ``` Cookie: .AspNetCore.Antiforgery.XXXXX=some-token-value; ``` Despite all of this, the validation fails. I've tried different browsers and cleared the cookies but the scenario continues. Is there something I'm missing in my configuration or implementation? Any insights would be greatly appreciated. My development environment is macOS. Any ideas what could be causing this?