ValidateAntiForgeryToken in ASP.NET Core
Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Enable anti-forgery middleware
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.Use(async (context, next) =>
{
// Generates an anti-forgery token
var antiForgery = context.RequestServices.GetRequiredService();
var tokens = antiForgery.GetTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
await next();
});
// Configure endpoints
app.MapControllers();
app.Run();
Controller
[HttpPost]
[ValidateAntiForgeryToken] // Validates the anti-forgery token
public IActionResult SubmitForm(string someInput)
{
// Process the form data
return RedirectToAction("Index");
}
Razor View
@Html.AntiForgeryToken()
AJAX Requests
$.ajax({
type: "POST",
url: "/MyController/SubmitForm",
data: {
someInput: "value"
},
headers: {
"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() // Include the token
},
success: function (response) {
// Handle success
}
});