dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.6k stars 25.29k forks source link

Describe how to require antiforgery validation on an API controller #33740

Open AnthonyMastrean opened 3 weeks ago

AnthonyMastrean commented 3 weeks ago

Description

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 }

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 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) { ... }
}

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

tdykstra commented 2 weeks ago

@MackinnonBuck Can you help with documenting [RequireAntiforgeryToken] or do you know who can?