I am wondering if anyone can help me. I am trying to get [ValidateAntiForgeryToken]
action method to fire and it appears not be. I was trying to check if the anti forgery token logic was actually doing anything and it appears not to be, unless I have setup it up incorrectly or I am just missing something obvious.
So inside the form I comment out
@Html.AntiForgeryToken()
while still leaving in place
[ValidateAntiForgeryToken]
on the controller. I get no error despite the fact there is no token (if there is no token it should it not fail and cause / throw an error) and the model state is valid (which I seems to be normal for this case). Please see basic example below:
private static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddAntiforgery(options => options.HeaderName = "XSRF-TOKEN");
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SubmitForm(FormModel form)
{
if (ModelState.IsValid)
{
}
return RedirectToAction("Index");
}
<form asp-action="SubmitForm" asp-controller="Home" method="post">
@* @Html.AntiForgeryToken() *@
<button type="submit">Submit</button>
</form>
So to sum up I am trying to get the anti forgery token to work.