Repository navigation
Description
Is there an existing issue for this?
- I have searched the existing issues
Is your feature request related to a problem? Please describe the problem.
Implement a modern, no-token-based CSRF protection algorithm using Fetch Metadata headers (Sec-Fetch-Site) as the primary defense, with fallback to the existing token-based approach for legacy clients.
For example in Go 1.25 a type CrossOriginProtection appeared.
Describe the solution you'd like
Fetch Metadata headers are widely available and works across many devices and browser versions. It’s been available across browsers since March 2023. See compatibility at Sec-Fetch-Site docs.
New algorithm is also not dependant on DataProtection, so it should be nearly no-op and more performant than the token-based approach.
The algorithm boils down to the following steps:
- Allow all GET, HEAD, or OPTIONS requests
These are safe methods, and are assumed not to change state at various layers of the stack already. - If the Origin header matches an allow-list of trusted origins, allow the request.
Trusted origins should be configured as full origins (e.g. https://example.com) and compared by simple equality with the header value. - If the Sec-Fetch-Site header is present, if its value is same-origin or none, allow the request; otherwise, reject the request.
This secures all major up-to-date browsers for sites hosted on trustworthy (HTTPS or localhost) origins. - If neither the Sec-Fetch-Site nor the Origin headers are present, allow the request.
These requests are not from (post-2020) browsers, and can’t be affected by CSRF. - If the Origin header’s host (including the port) matches the Host header, allow the request, otherwise reject it.
This is either a request to an HTTP origin, or by an out-of-date browser.
Additional context
Proposal
Antiforgery today works and is deployed accross many aspnetcore apps. Introducing a conceptually new algorithm as a separate package, API and middleware will be burden for every user to opt-in to the new behavior.
Instead, I am proposing a modification to the provided algorithm (as above) to use existing token-based Antiforgery as a fallback mechanism.
The pseudo code is the following:
public CrossOriginValidationResult Validate(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
var request = context.Request;
var headers = request.Headers;
// Get the Origin header value
var origin = headers.Origin.ToString();
var hasOrigin = !string.IsNullOrEmpty(origin) && !string.Equals(origin, "null", StringComparison.OrdinalIgnoreCase);
// Step 1: Check if Origin is in trusted origins list
if (hasOrigin && IsTrustedOrigin(origin))
{
return CrossOriginValidationResult.Allowed;
}
// Step 2: Check Sec-Fetch-Site header (modern browsers)
var secFetchSite = headers[SecFetchSiteHeaderName].ToString();
if (!string.IsNullOrEmpty(secFetchSite))
{
// "same-origin" means the request is from the same origin
// "none" means the request was user-initiated (e.g., bookmark, typed URL)
if (string.Equals(secFetchSite, SecFetchSiteSameOrigin, StringComparison.OrdinalIgnoreCase) ||
string.Equals(secFetchSite, SecFetchSiteNone, StringComparison.OrdinalIgnoreCase))
{
return CrossOriginValidationResult.Allowed;
}
// "cross-site" or "same-site" means the request is from a different origin/site
// This is a potential CSRF attack
if (string.Equals(secFetchSite, SecFetchSiteCrossSite, StringComparison.OrdinalIgnoreCase) ||
string.Equals(secFetchSite, SecFetchSiteSameSite, StringComparison.OrdinalIgnoreCase))
{
return CrossOriginValidationResult.Denied;
}
// Unknown Sec-Fetch-Site value - treat as suspicious
return CrossOriginValidationResult.Denied;
}
// Step 3: Fallback to Origin vs Host comparison (older browsers)
if (hasOrigin)
{
if (OriginMatchesHost(origin, headers.Host.ToString()))
{
return CrossOriginValidationResult.Allowed;
}
// Origin doesn't match Host - this is a cross-origin request
return CrossOriginValidationResult.Denied;
}
// Step 4: Neither Sec-Fetch-Site nor Origin is present
// This could be:
// - A non-browser request (curl, Postman, API client)
// - A very old browser
// - A privacy extension that strips headers
// Return Unknown to trigger fallback to token-based validation
return CrossOriginValidationResult.Unknown;
}API Proposal
+ public class CrossOriginAntiforgeryOptions
+{
+ public IList<string> TrustedOrigins { get; } = new List<string>();
+ public bool FallbackToTokenValidation { get; set; } = true;
+ }
+ public enum CrossOriginValidationResult
+ {
+ Allowed,
+ Denied,
+ Unknown
+ }
+ public interface ICrossOriginAntiforgery
+ {
+ public CrossOriginValidationResult Validate(HttpContext context);
+ }
Activity
fowl2 commentedon Feb 21, 2026
Would it make sense to have a “fail safe” setting to fail at step 4 - ie. always require Sec-Fetch-Site and/or Origin headers - to catch old browsers? Adding an additional static header shouldn’t be too big of a burden for many non-browser clients.
DeagleGross commentedon Feb 23, 2026
We did not come up with the specific API yet, but I hope we will build it in a way, that it will be configurable. Even with current code observing
CrossOriginValidationResult.Unknownwould mean client is using an old browser, and ideally developer could make a decision to validate the request with the token-based CSRF algorithm (current ASP.NET Core's Antiforgery).Within your usage do you expect to start blocking requests from old-browsers?
fowl2 commentedon Feb 25, 2026
Yes, I'd expect for simplicity/reducing test cases/"defense in depth" to just block requests missing the header. Very old browsers are a risk anyway.
Make it the default and have one less thing to worry about, if we're keen 😀.
DeagleGross commentedon Mar 20, 2026
API Proposal
If you want to look how code looks: #65887
Current state of code
Today we have
Antiforgerypackage dedicated to guarding against CSRF attacks. Antiforgery uses token-based approach. And the usage is simple:That is it.
Requirements / Thoughts
Requirements for this API are:
I was thinking about if we should have some flag or enum to configure the order, but it is not very pretty. I think we should have such assumptions about API:
UseAntiforgery()should be the API we are recommending. And we could be able to change it going forward (even though this is a behavioral change). By default to get the best and secure option - it is the API to use.UseTokenBasedAntiforgery()- the former API to enable only token-based Antiforgery middlewareUseCrossOriginAntiforgery()- the new API to enable Sec-Fetch-* header based Antiforgery middlewareThat gives full control to the user, and we are happy just providing the API for the user to make their own decision.
API
Firstly, adding a new namespace for "CrossOrigin" Antiforgery. Name is "copied" from the Go implementation - it seems suitable.
Adding a new type of validation result.
and a new interface to call validate on HttpContext:
There also should be options on CrossOriginAntiforgery:
That is all for the implementation part of API. For the registrations and usage:
required change to have
AddAntiforgery()on the new CrossOrigin way + an overload to setup both.AddAntiforgery()without parameters will register both by default.namespace Microsoft.Extensions.DependencyInjection; public static class AntiforgeryServiceCollectionExtensions { + public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action<AntiforgeryOptions> setupAction, Action<CrossOriginAntiforgeryOptions> crossOriginSetupAction); + public static IServiceCollection AddCrossOriginAntiforgery(this IServiceCollection services); + public static IServiceCollection AddCrossOriginAntiforgery(this IServiceCollection services, Action<CrossOriginAntiforgeryOptions> setupAction); }This gives opportunity to setup
AddAntiforgery(opt1 => {}, crossOriginOpt => {})with both approaches, plus only add cross-origin one. Unfortunately, since token-based is called "Antiforgery", then it will be of the same name as the default API registering both approaches.For the
UseAntiforgery()same picture:namespace Microsoft.AspNetCore.Builder; public static class AntiforgeryApplicationBuilderExtensions { + public static IApplicationBuilder UseTokenBasedAntiforgery(this IApplicationBuilder builder); + public static IApplicationBuilder UseCrossOriginAntiforgery(this IApplicationBuilder builder); }default
AddAntiforgery()will be using both in order CrossOrigin -> TokenBased.Usage Examples
With fallback:
cross-origin only:
token-based only:
DeagleGross commentedon Apr 21, 2026
API Proposal V2: Cross-Origin Protection via Fetch Metadata Headers
Motivation
After feedback and iteration on the initial design, I identified several problems with the original approach of adding cross-origin protection inside the
Antiforgerypackage:Required explicit middleware — The original design introduced
UseCrossOriginAntiforgery()andUseTokenBasedAntiforgery(). Users had to choose and compose middlewares. Cross-origin protection didn't work without middleware, even though MVC/Razor Pages have their own filter-based validation path that bypasses middleware entirely.Didn't "just work" — MVC controllers using
[ValidateAntiForgeryToken]callIAntiforgery.ValidateRequestAsync()directly through authorization filters. The cross-origin check was only in the middleware path, so the MVC filter path got zero protection.Heavy dependency chain for a lightweight check — The
Antiforgerypackage depends onDataProtection(cryptography, key management, XML encryption). Cross-origin validation is just synchronous HTTP header reads — it needs none of that. Auto-enabling it for all apps (including AOT minimal APIs) would pullDataProtectioninto every binary, violating the "pay for what you use" principle and bloating trimmed/AOT builds.Separate options class —
CrossOriginAntiforgeryOptionswas a new options type alongsideAntiforgeryOptions, requiring newAddCrossOriginAntiforgery()registration methods and dual-configure patterns.Design Principles
AddAntiforgery()orUseAntiforgery().DataProtection,Antiforgery, or any heavy package. Must not prevent trimming of unused assemblies.AddAntiforgery()+UseAntiforgery()), the token-based middleware is still the fallback (unless completely disabled cross-origin).[IgnoreAntiforgeryToken](MVC/Pages) and.DisableAntiforgery()(Minimal APIs) continue to work for both token-based and cross-origin protection.ICrossOriginProtectionfrom DI.Algorithm
The validation algorithm runs synchronously on every non-safe request to a protected endpoint:
Step 5 provides fallback for older browsers that don't send
Sec-Fetch-Site. Step 7 ensures API clients, mobile apps, and tools likecurlaren't blocked.Proposed API
Public types in
Microsoft.AspNetCore.Http.AbstractionsPublic types — options and DI registration
(Assembly placement discussed below — see "Assembly Placement Options".)
Internal implementation (shared source)
Enablement and Configuration
Cross-origin protection has no
Enabledboolean property on the options class. Following the HostFiltering pattern, enablement is controlled by configuration, not by a runtime flag that the implementation checks.Default behavior
ICrossOriginProtectionis registered automatically byAddRoutingCore(). Cross-origin validation runs for every endpoint withIAntiforgeryMetadata.RequiresValidation == true, as an independent security layer alongside (not instead of) token-based antiforgery.Configuration via appsettings.json
TrustedOrigins can be configured from
appsettings.json, following the same pattern as HostFiltering'sAllowedHosts:{ "CrossOriginProtection": { "TrustedOrigins": "https://admin.internal;https://partner.com" } }A
PostConfigure<CrossOriginProtectionOptions>inWebHost.ConfigureWebDefaultsWorkerreads fromIConfiguration["CrossOriginProtection:TrustedOrigins"]and splits on;— the same semicolon-delimited format used byAllowedHosts.Disabling globally via configuration
To disable cross-origin protection entirely (e.g., during local development or for apps that exclusively use token-based antiforgery):
{ "CrossOriginProtection": "false" }When this configuration is present,
WebHost.ConfigureWebDefaultsWorkerremoves theICrossOriginProtectionservice from DI. Endpoints with antiforgery metadata will then requireUseAntiforgery()— the .NET 10 behavior.This follows the same principle as
HostFilteringMiddleware: the feature is always present by default, but its presence is determined by configuration, not by a boolean flag on the options class. The implementation never checksif (enabled)— it either exists in DI or doesn't.Disabling per-endpoint
The existing
DisableAntiforgery()extension works for cross-origin protection as well:This removes
IAntiforgeryMetadata.RequiresValidation, so cross-origin protection won't run for that endpoint.Programmatic configuration
The standard
IOptions<T>layering applies — programmaticConfigure<T>calls take priority overPostConfigure<T>from configuration.TrustedOrigins vs CORS Origins
TrustedOriginsis deliberately separate from CORSAllowedOriginsbecause they answer different questions:Access-Control-Allow-Originresponse headerSec-Fetch-Site/Origin<form>POSTfetch()with credentialsAllowCredentials()A common CORS configuration allows a partner SPA to read API responses — but that does NOT mean the partner should be trusted for CSRF-sensitive state-changing operations. The overlap between CORS and CSRF trusted origins is coincidental, not structural.
Most applications need zero configuration — same-origin requests are allowed automatically by
Sec-Fetch-Site.TrustedOriginsis only for the rare case where a different origin needs to make authenticated POST/PUT/DELETE requests.Integration Model
Two independent layers
Cross-origin protection and token-based antiforgery are independent layers, not alternatives:
Both layers run independently. If both are enabled, both must pass. Cross-origin protection is never skipped because token-based antiforgery is also configured.
EndpointMiddleware integration
EndpointMiddlewareruns the cross-origin check for every endpoint that requires antiforgery validation:Concern: "real check" in a "setup-check" spot
EndpointMiddleware's existing checks (authorization, CORS, antiforgery) are setup validation guards — they verify middleware was registered, not perform actual security checks. Embedding a real security check here is a departure from that pattern.MVC handles this differently: antiforgery filters (
ValidateAntiforgeryTokenAuthorizationFilter) callIAntiforgery.ValidateRequestAsync()directly during the filter pipeline. MVC never relies onEndpointMiddlewarefor antiforgery — it's all in filters.For Minimal APIs, there is no filter pipeline, so the integration point options are:
IStartupFilter(HostFiltering pattern) — cleaner separation, but introduces a middleware the user doesn't seeUseCrossOriginProtection()— rejected per colleague feedback ("don't introduce new middlewares")The proposal uses option 1 for simplicity. If API review prefers cleaner separation, option 2 (IStartupFilter) is an alternative that follows established precedent.
Coverage Across Frameworks
EndpointMiddlewareICrossOriginProtection.Validate()for every endpoint with antiforgery metadataDefaultAntiforgery.ValidateRequestAsync()ICrossOriginProtectionfrom DI; runs cross-origin check as an independent layer alongside token validationAutoValidateAntiforgeryTokenAuthorizationFilter→ValidateRequestAsync()→ cross-origin checkAntiforgeryMiddleware→ValidateRequestAsync()→ cross-origin checkMVC/Pages/Blazor integration requires changes to
DefaultAntiforgery.ValidateRequestAsync()in theMicrosoft.AspNetCore.Antiforgeryassembly, which already has access toICrossOriginProtectionviaHttp.Abstractions.Assembly Placement Options
The interface (
ICrossOriginProtection,CrossOriginAntiforgeryResult) lives inMicrosoft.AspNetCore.Http.Abstractions— this is the lowest common dependency that both Routing and Antiforgery reference, giving maximum reachability.The implementation and options need a home. Available options:
Option A:
Microsoft.AspNetCore.RoutingCurrent implementation.
EndpointMiddlewareis the Minimal API integration point, andAddRoutingCore()handles DI registration.RoutingOption B: New
Microsoft.AspNetCore.CrossOriginProtectionA small, focused assembly under
src/Middleware/CrossOriginProtection/following the HostFiltering/HttpsPolicy pattern.Option C:
Microsoft.AspNetCore.Http.ExtensionsBoth Routing and Antiforgery reference this assembly.
Option D:
Microsoft.AspNetCore.AntiforgeryWhere token-based antiforgery lives today.
Option E:
Microsoft.AspNetCore.HttpThe core HTTP implementation assembly (DefaultHttpContext, etc.).
Usage Examples
Default (zero-config) — Minimal API
With trusted origins (programmatic)
With trusted origins (appsettings.json)
{ "CrossOriginProtection": { "TrustedOrigins": "https://admin.internal;https://mobile-bff.example.com" } }Opt out per-endpoint
Disable globally via configuration
{ "CrossOriginProtection": "false" }Combined with token-based antiforgery
DeagleGross commentedon Apr 22, 2026
Notes by @halter73:
Enabledin options is not ideal, we can enable it by default on Configuration layer (HostOptions or IConfiguration as for AllowedHosts. Then we will either add the middleware or not.Routing), maybe another dll?CrossOriginValidationResultrename to haveAntiforgeryin the name to properly tell the storyUPD: Updated proposal above applying discussed suggestions.
1 remaining item
dotnet-policy-service commentedon Apr 23, 2026
Thank you for submitting this for API review. This will be reviewed by @dotnet/aspnet-api-review at the next meeting of the ASP.NET Core API Review group. Please ensure you take a look at the API review process documentation and ensure that:
halter73 commentedon Apr 30, 2026
API Review Notes:
CrossOriginin names likeICrossOriginProtectionsounds too much like CORS and not like it's anti-CSRF related.CrossSitebetter orCrossSiteRequestForgeryProtection(orCsrfProtection)CorsOptionsTrustedOriginslater if people want to use the new middleware to lock down cross-site form posts more than CORS requests in generalHttpContext.Request.FormRegarding the following config, we think that putting
EnableorDisablein the config name is a good idea.{ "DisableCsrfProtection": true }We think this this is better. We don't think we necessarily need a C# API for this, but if we do, we should look into any options types that are consumed by the
GenericWebHostBuilderand try to treat this similarly to the host filtering middleware getting implicitly added.DeagleGross commentedon May 26, 2026
Updates to API shape
ICorsPolicyProvider.GetPolicyAsyncis the public extensibility point we need to call.ValueTask<CsrfProtectionResult>is the right return type.DeagleGross commentedon May 26, 2026
Updates to API shape
ICorsPolicyProvider.GetPolicyAsyncis the public extensibility point we need to call.ValueTask<CsrfProtectionResult>is the right return type.Remove redundant app.UseAntiforgery() from Blazor Web templates (#67119)