The classic API controller, using [ApiController] and inheriting ControllerBase, does not participate in any of the documented methods of antiforgery validation.
MVC controllers (inheriting Controller) use the [ValidateAntiforgeryToken] attribute and minimal APIs are covered by the new antiforgery middleware, which depends on the following expression:
endpoint?.Metadata.GetMetadata<IAntiforgeryMetadata>() is { RequiresValidation: true }
From what I can tell, there's some source generated code that performs some kind of "has form body" check and sets the IAntiforgeryMetadata.RequiresValidation property to true... but only for minimal APIs.
Only the new [RequireAntiforgeryToken] attribute sets the property and is valid on API controllers, but it's entirely missing from the documentation!
[ApiController]
public class ExampleController : ControllerBase
{
[HttpPost]
[RequireAntiforgeryToken]
public void Post([FromForm] IFormFile form) { ... }
}
Description
The classic API controller, using
[ApiController]
and inheritingControllerBase
, does not participate in any of the documented methods of antiforgery validation.MVC controllers (inheriting
Controller
) use the[ValidateAntiforgeryToken]
attribute and minimal APIs are covered by the new antiforgery middleware, which depends on the following expression:https://github.com/dotnet/aspnetcore/blob/main/src/Antiforgery/src/AntiforgeryMiddleware.cs#L31-L34
From what I can tell, there's some source generated code that performs some kind of "has form body" check and sets the
IAntiforgeryMetadata.RequiresValidation
property totrue
... but only for minimal APIs.Only the new
[RequireAntiforgeryToken]
attribute sets the property and is valid on API controllers, but it's entirely missing from the documentation!Page URL
https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-8.0
Content source URL
https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/security/anti-request-forgery.md
Document ID
bffca13c-223f-c61f-9cb2-9da8811eecfa
Article author
@tdykstra
Related Issues