dotnet / dotnet/AspNetCore.Docs

Describe how to require antiforgery validation on an API controller

Open
#33,740 1 comment 1 reaction 1 assignee Claimed by @tdykstra View on GitHub
:watch: Not Triaged aspnet-core/svc security/subsvc Source - Docs.ms
Dominant language
C#
Stars
13.1k
Forks
24.6k
Avg merge
1d 2h
Merged PRs (30d)
109

Description

### Description

The classic [API controller](https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-8.0), 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:

```csharp
endpoint?.Metadata.GetMetadata() 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!

```csharp
[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](https://github.com/dotnet/AspNetCore.Docs/issues?q=is%3Aissue+is%3Aopen+bffca13c-223f-c61f-9cb2-9da8811eecfa)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.