I suppose you would like Antiforgery to work with Ajax scripts. The following is an example:
In Startup.cs:
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
Filter for creating anti-corrosion token cookies:
public class GenerateAntiforgeryTokenCookieForAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
var antiforgery = context.HttpContext.RequestServices.GetService<IAntiforgery>();
var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
context.HttpContext.Response.Cookies.Append(
"XSRF-TOKEN",
tokens.RequestToken,
new CookieOptions() { HttpOnly = false });
}
}
Filter Usage:
[HttpGet]
[GenerateAntiforgeryTokenCookieForAjax]
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product product)
{
source
share