-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Description
Background and Motivation
MVC currently supports anti-forgery token validation via an endpoint filter. Similar constructs do not exist for minimal APIs. This proposal outlines support for an anti-forgery middleware, similar to CORS or authorization middleware, that will run anti-forgery token checks on endpoints with the appropriate metadata.
Proposed API
All APIs are net new.
// Assembly: Microsoft.AspNetCore.Antiforgery
namespace Microsoft.AspNetCore.Builder;
public static class AntiforgeryApplicationBuilderExtensions
{
public static IApplicationBuilder UseAntiforgery(this IApplicationBuilder builder) { }
}
Note: The IAntiforgeryMetadata
interface needs to reside in the Http.Abstractions assembly so that it can be consumed by the RequestDelegateFactory, the endpoint middleware, and Blazor SSR components.
// Assembly: Microsoft.AspNetCore.Http.Abstractions
namespace Microsoft.AspNetCore.Antiforgery;
public interface IAntiforgeryMetadata
{
public bool Required { get; }
}
// Assembly: Microsoft.AspNetCore.Antiforgery
namespace Microsoft.AspNetCore.Antiforgery;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequireAntiforgeryTokenAttribute(bool required = true) : Attribute, IAntiforgeryMetadata
{
public bool Required { get; }
}
// Assembly: Microsoft.AspNetCore.Antiforgery
namespace Microsoft.AspNetCore.Antiforgery;
public interface IAntiforgeryValidationFeature
{
public bool IsValid { get; }
public AntiforgeryValidationException? Exception { get; }
}
Usage Examples
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAntiforgery();
var app = builder.Build();
app.UseAntiforgery();
// Anti-forgery token validation happens for this endpoint
app.MapPost("/todo", ([FromForm] Todo todo) => Results.Ok(todo));
app.Run();
Alternative Designs
This API proposal does not include public default implementations of antiforgery metadata types (e.g. AntiforgeryMetadata : IAntiforgeryMetadata
) or extension methods for disabling anti-forgery.
Anti-forgery metadata with anti-forgery enabled is automatically added for endpoints that contain a source coming from a form. We anticipate that users will implement their own extension methods for disabling anti-forgery on a given endpoint.
public static RouteHandlerBuilder DisableAntiforgery(this RouteHandlerBuilder builder)
{
builder.WithMetadata(new RequireAntiforgeryTokenAttribute(false));
return builder;
}
Risks
Nothing ventured, nothing gained.