Skip to content

New Cross-Site Request Forgery Algorithm based on Fetch Metadata headers #65127

Description

@DeagleGross

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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);
+ }

Additional links

Activity

  1. added
    needs-area-label
    on Jan 19, 2026
  2. added
    api-suggestion
    and removed
    needs-area-label
    on Jan 19, 2026
  3. added this to the .NET 11 Planning milestone on Jan 26, 2026
  4. self-assigned this
    on Feb 20, 2026
  5. fowl2 commented on Feb 21, 2026

    @fowl2

    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.

  6. DeagleGross commented on Feb 23, 2026

    @DeagleGross
    MemberAuthor

    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.

    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.Unknown would 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?

  7. fowl2 commented on Feb 25, 2026

    @fowl2

    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 😀.

  8. DeagleGross commented on Mar 20, 2026

    @DeagleGross
    MemberAuthor

    API Proposal

    If you want to look how code looks: #65887

    Current state of code

    Today we have Antiforgery package dedicated to guarding against CSRF attacks. Antiforgery uses token-based approach. And the usage is simple:

    builder.Services.AddAntiforgery(); // registers services related to Antiforgery
    var app = builder.Build();
    app.UseAntiforgery(); // adds middleware
    

    That is it.

    Requirements / Thoughts

    Requirements for this API are:

    • it should be as modern as possible and secure by default
    • it should be flexible to allow as customs setup as possible. For example there are clients who support mostly old browsers, and they dont care about new approach - they should be able to use only token-based approach. And viceversa. It should be possible to enable both in any order.

    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 middleware
    • UseCrossOriginAntiforgery() - the new API to enable Sec-Fetch-* header based Antiforgery middleware

    That 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.

    + namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin;
    
    + public enum CrossOriginValidationResult
    {
    +     Allowed,
    +    Denied,
    +    Unknown
    }

    and a new interface to call validate on HttpContext:

    + namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin;
    
    +public interface ICrossOriginAntiforgery
    {
    +    CrossOriginValidationResult Validate(HttpContext context);
    }

    There also should be options on CrossOriginAntiforgery:

    + namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin;
    
    + public class CrossOriginAntiforgeryOptions
    {
    +    public IList<string> TrustedOrigins { get; } = new List<string>();
    }

    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:

    builder.Services.AddAntiforgery();
    var app = builder.Build();
    app.UseAntiforgery(); // cross-origin + token fallback

    cross-origin only:

    builder.Services.AddCrossOriginAntiforgery();
    app.UseCrossOriginAntiforgery();

    token-based only:

    builder.Services.AddAntiforgery((AntiforgeryOptions _) => { });
    app.UseTokenBasedAntiforgery();
  9. DeagleGross commented on Apr 21, 2026

    @DeagleGross
    MemberAuthor

    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 Antiforgery package:

    1. Required explicit middleware — The original design introduced UseCrossOriginAntiforgery() and UseTokenBasedAntiforgery(). 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.

    2. Didn't "just work" — MVC controllers using [ValidateAntiForgeryToken] call IAntiforgery.ValidateRequestAsync() directly through authorization filters. The cross-origin check was only in the middleware path, so the MVC filter path got zero protection.

    3. Heavy dependency chain for a lightweight check — The Antiforgery package depends on DataProtection (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 pull DataProtection into every binary, violating the "pay for what you use" principle and bloating trimmed/AOT builds.

    4. Separate options class — CrossOriginAntiforgeryOptions was a new options type alongside AntiforgeryOptions, requiring new AddCrossOriginAntiforgery() registration methods and dual-configure patterns.

    Design Principles

    • Auto-enabled, zero configuration — Cross-origin protection works out of the box for every ASP.NET Core app on .NET 11, without calling AddAntiforgery() or UseAntiforgery().
    • No new middlewares — No middleware that users must wire up in the correct order.
    • AOT/Trim safe — No dependency on DataProtection, Antiforgery, or any heavy package. Must not prevent trimming of unused assemblies.
    • Composable with existing antiforgery — When users opt into token-based antiforgery (AddAntiforgery() + UseAntiforgery()), the token-based middleware is still the fallback (unless completely disabled cross-origin).
    • Existing opt-out mechanisms work — [IgnoreAntiforgeryToken] (MVC/Pages) and .DisableAntiforgery() (Minimal APIs) continue to work for both token-based and cross-origin protection.
    • Explicit invocation supported — Users who need to call cross-origin validation from their own middleware, filters, or handlers can inject ICrossOriginProtection from DI.

    Algorithm

    The validation algorithm runs synchronously on every non-safe request to a protected endpoint:

    1. Safe methods (GET, HEAD, OPTIONS, TRACE) → Allow
    2. Origin in TrustedOrigins list → Allow  
    3. Sec-Fetch-Site == "same-origin" or "none" → Allow
    4. Sec-Fetch-Site == "cross-site" / "same-site" / other → Deny
    5. No Sec-Fetch-Site, but Origin header matches request host → Allow
    6. No Sec-Fetch-Site, Origin doesn't match → Deny
    7. Neither header present (non-browser client) → Allow
    

    Step 5 provides fallback for older browsers that don't send Sec-Fetch-Site. Step 7 ensures API clients, mobile apps, and tools like curl aren't blocked.

    Proposed API

    Public types in Microsoft.AspNetCore.Http.Abstractions

    namespace Microsoft.AspNetCore.Antiforgery;
    
    /// <summary>
    /// Provides cross-origin request protection based on Fetch Metadata headers
    /// (Sec-Fetch-Site) and Origin header validation. This is a lightweight
    /// defense against CSRF attacks that does not require tokens or DataProtection.
    /// </summary>
    public interface ICrossOriginProtection
    {
        CrossOriginAntiforgeryResult Validate(HttpContext context);
    }
    
    /// <summary>
    /// Represents the result of cross-origin antiforgery request validation.
    /// </summary>
    public enum CrossOriginAntiforgeryResult
    {
        Allowed,
        Denied
    }

    Public types — options and DI registration

    (Assembly placement discussed below — see "Assembly Placement Options".)

    namespace Microsoft.AspNetCore.Antiforgery;
    
    /// <summary>
    /// Configuration for cross-origin request protection.
    /// </summary>
    public class CrossOriginProtectionOptions
    {
        /// <summary>
        /// Origins that are allowed for cross-origin state-changing requests.
        /// Format: "scheme://host[:port]" (e.g., "https://admin.internal").
        /// Most applications don't need this — same-origin requests are allowed
        /// automatically via Sec-Fetch-Site header validation.
        /// </summary>
        public IList<string> TrustedOrigins { get; } = new List<string>();
    }
    namespace Microsoft.Extensions.DependencyInjection;
    
    public static IServiceCollection ConfigureCrossOriginProtection(
        this IServiceCollection services,
        Action<CrossOriginProtectionOptions> configureOptions);

    Internal implementation (shared source)

    // src/Shared/CrossOriginProtection/CrossOriginRequestValidator.cs
    // Compiled into multiple assemblies via shared source pattern
    internal static class CrossOriginRequestValidator
    {
        internal static bool IsRequestAllowed(HttpContext context, IList<string> trustedOrigins);
    }

    Enablement and Configuration

    Cross-origin protection has no Enabled boolean 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

    ICrossOriginProtection is registered automatically by AddRoutingCore(). Cross-origin validation runs for every endpoint with IAntiforgeryMetadata.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's AllowedHosts:

    {
      "CrossOriginProtection": {
        "TrustedOrigins": "https://admin.internal;https://partner.com"
      }
    }

    A PostConfigure<CrossOriginProtectionOptions> in WebHost.ConfigureWebDefaultsWorker reads from IConfiguration["CrossOriginProtection:TrustedOrigins"] and splits on ; — the same semicolon-delimited format used by AllowedHosts.

    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.ConfigureWebDefaultsWorker removes the ICrossOriginProtection service from DI. Endpoints with antiforgery metadata will then require UseAntiforgery() — 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 checks if (enabled) — it either exists in DI or doesn't.

    Disabling per-endpoint

    The existing DisableAntiforgery() extension works for cross-origin protection as well:

    app.MapPost("/webhook", HandleWebhook).DisableAntiforgery();

    This removes IAntiforgeryMetadata.RequiresValidation, so cross-origin protection won't run for that endpoint.

    Programmatic configuration

    builder.Services.ConfigureCrossOriginProtection(options =>
    {
        options.TrustedOrigins.Add("https://admin.internal");
    });

    The standard IOptions<T> layering applies — programmatic Configure<T> calls take priority over PostConfigure<T> from configuration.

    TrustedOrigins vs CORS Origins

    TrustedOrigins is deliberately separate from CORS AllowedOrigins because they answer different questions:

    Concern CORS AllowedOrigins CSRF TrustedOrigins
    Question "Can JS from this origin read my responses?" "Can this origin make state-changing requests?"
    Mechanism Access-Control-Allow-Origin response header Block/allow based on Sec-Fetch-Site / Origin
    <form> POST Not blocked (simple request) Blocked if cross-origin
    fetch() with credentials Requires AllowCredentials() Covered by Sec-Fetch-Site

    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. TrustedOrigins is 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:

    Request → Cross-Origin Protection (default, always-on) → Token-based Antiforgery (opt-in)
                   ↓                                              ↓
              Sec-Fetch-Site / Origin                         Cookie + token
              Lightweight, synchronous                        DataProtection, async
              Enabled by default for all apps                 User explicitly adds
    

    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

    EndpointMiddleware runs the cross-origin check for every endpoint that requires antiforgery validation:

    // EndpointMiddleware (simplified)
    if (endpoint requires antiforgery)
    {
        // Cross-origin runs as an independent layer, regardless of
        // whether token-based antiforgery middleware is in the pipeline
        if (ICrossOriginProtection is registered)
        {
            var result = crossOriginProtection.Validate(httpContext);
            if (result == Denied) → 400 Bad Request
            // Allowed → proceed
        }
    
        // Separate concern: if no cross-origin protection AND no antiforgery
        // middleware, fail closed with actionable error (.NET 10 behavior)
        if (no ICrossOriginProtection && no antiforgery middleware marker)
        {
            throw "Configure your app with UseAntiforgery()..."
        }
    }

    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) call IAntiforgery.ValidateRequestAsync() directly during the filter pipeline. MVC never relies on EndpointMiddleware for antiforgery — it's all in filters.

    For Minimal APIs, there is no filter pipeline, so the integration point options are:

    1. EndpointMiddleware (current approach) — pragmatic, no new middleware, the check is synchronous and cheap
    2. Auto-registered middleware via IStartupFilter (HostFiltering pattern) — cleaner separation, but introduces a middleware the user doesn't see
    3. Explicit middleware — user calls UseCrossOriginProtection() — 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

    Framework Integration Point How
    Minimal APIs EndpointMiddleware Calls ICrossOriginProtection.Validate() for every endpoint with antiforgery metadata
    MVC Controllers DefaultAntiforgery.ValidateRequestAsync() Resolves ICrossOriginProtection from DI; runs cross-origin check as an independent layer alongside token validation
    Razor Pages Same as MVC AutoValidateAntiforgeryTokenAuthorizationFilter → ValidateRequestAsync() → cross-origin check
    Blazor Same as MVC AntiforgeryMiddleware → ValidateRequestAsync() → cross-origin check

    MVC/Pages/Blazor integration requires changes to DefaultAntiforgery.ValidateRequestAsync() in the Microsoft.AspNetCore.Antiforgery assembly, which already has access to ICrossOriginProtection via Http.Abstractions.

    Assembly Placement Options

    The interface (ICrossOriginProtection, CrossOriginAntiforgeryResult) lives in Microsoft.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.Routing

    Current implementation. EndpointMiddleware is the Minimal API integration point, and AddRoutingCore() handles DI registration.

    Aspect Details
    Pro No new assembly; integration point already here; every app references Routing
    Con Cross-origin protection is not a routing concern; there is a "setup-check", not actual requst processing check

    Option B: New Microsoft.AspNetCore.CrossOriginProtection

    A small, focused assembly under src/Middleware/CrossOriginProtection/ following the HostFiltering/HttpsPolicy pattern.

    Aspect Details
    Pro Clean separation; single responsibility
    Pro Follows established precedent (HostFiltering: 5 files, ~200 LoC)
    Pro Minimal dependencies (Http.Abstractions + Options only)
    Pro Can be referenced by both Routing and Antiforgery
    Con New assembly in shared framework

    Option C: Microsoft.AspNetCore.Http.Extensions

    Both Routing and Antiforgery reference this assembly.

    Aspect Details
    Pro Already a shared dependency; no new assembly
    Con Http.Extensions is for HTTP helper/extension methods, not security services

    Option D: Microsoft.AspNetCore.Antiforgery

    Where token-based antiforgery lives today.

    Aspect Details
    Pro Conceptually the right domain
    Con Forces DataProtection into every app's dependency graph. Not AOT friendly

    Option E: Microsoft.AspNetCore.Http

    The core HTTP implementation assembly (DefaultHttpContext, etc.).

    Aspect Details
    Pro Widely referenced; no new assembly
    Con Http assembly is for HTTP primitives, not security middleware

    Usage Examples

    Default (zero-config) — Minimal API

    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    
    // No AddAntiforgery(), no UseAntiforgery() needed!
    app.MapPost("/transfer", (TransferRequest req) => { /* ... */ });
    
    app.Run();
    // Cross-origin protection is automatic for POST endpoints

    With trusted origins (programmatic)

    builder.Services.ConfigureCrossOriginProtection(options =>
    {
        options.TrustedOrigins.Add("https://admin.internal");
        options.TrustedOrigins.Add("https://mobile-bff.example.com");
    });

    With trusted origins (appsettings.json)

    {
      "CrossOriginProtection": {
        "TrustedOrigins": "https://admin.internal;https://mobile-bff.example.com"
      }
    }

    Opt out per-endpoint

    app.MapPost("/webhook", HandleWebhook).DisableAntiforgery();

    Disable globally via configuration

    {
      "CrossOriginProtection": "false"
    }

    Combined with token-based antiforgery

    builder.Services.AddAntiforgery();
    app.UseAntiforgery();
    // Both layers run independently:
    // 1. Cross-origin protection validates Sec-Fetch-Site / Origin headers
    // 2. Token-based antiforgery validates cookie + form token
    // A request must pass BOTH checks
  10. DeagleGross commented on Apr 22, 2026

    @DeagleGross
    MemberAuthor

    Notes by @halter73:

    1. Enabled in 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.
    2. Think about different place of implementation (not Routing), maybe another dll?
    3. Consider CrossOriginValidationResult rename to have Antiforgery in the name to properly tell the story
    4. See if we can reuse the CORS configuration. If yes, then we do not need the separate options?

    UPD: Updated proposal above applying discussed suggestions.

  11. 1 remaining item

  12. removed
    api-suggestion
    on Apr 23, 2026
  13. dotnet-policy-service commented on Apr 23, 2026

    @dotnet-policy-service
    Contributor

    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:

    • The PR contains changes to the reference-assembly that describe the API change. Or, you have included a snippet of reference-assembly-style code that illustrates the API change.
    • The PR describes the impact to users, both positive (useful new APIs) and negative (breaking changes).
    • Someone is assigned to "champion" this change in the meeting, and they understand the impact and design of the change.
  14. added
    on-roadmap
    on Apr 29, 2026
  15. halter73 commented on Apr 30, 2026

    @halter73
    Member

    API Review Notes:

    • Do we need to remove the DataProtection entirely to be AOT/trim-safe? Could we put it in the existing Microsoft.AspNetCore.Antiforgery package and keep AOT compatibility for the new APIs?
      • Otherwise, I think we should use a new dll, not put the logic in routing.
    • CrossOrigin in names like ICrossOriginProtection sounds too much like CORS and not like it's anti-CSRF related.
      • We like CrossSite better or CrossSiteRequestForgeryProtection (or CsrfProtection)
    • Regarding "TrustedOrigins vs CORS Origins", we think we should allow per-endpoint config, and we think this will be easier if we at least allow you to configure it via policies from CorsOptions
      • We can add TrustedOrigins later if people want to use the new middleware to lock down cross-site form posts more than CORS requests in general
    • Let's not put the implicit middleware adding in the routing middleware, that should only raise errors for missing middleware
    • Can we get away with no middleware? Could we just force people to use the service to read form data?
      • This could make things a lot harder for things reading HttpContext.Request.Form
    // Microsoft.AspNetCore.Http.Abstractions.dll
    namespace Microsoft.AspNetCore.Antiforgery;
    
    /// <summary>
    /// Provides cross-origin request protection based on Fetch Metadata headers
    /// (Sec-Fetch-Site) and Origin header validation. This is a lightweight
    /// defense against CSRF attacks that does not require tokens or DataProtection.
    /// </summary>
    public interface ICsrfProtection
    {
        CsrfProtectionResult Validate(HttpContext context);
    }
    
    /// <summary>
    /// Represents the result of cross-origin antiforgery request validation.
    /// </summary>
    public enum CsrfProtectionResult
    {
        Allowed,
        Denied
    }

    Regarding the following config, we think that putting Enable or Disable in 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 GenericWebHostBuilder and try to treat this similarly to the host filtering middleware getting implicitly added.

  16. added
    api-approved
    and removed
    api-ready-for-review
    on Apr 30, 2026
  17. DeagleGross commented on May 26, 2026

    @DeagleGross
    MemberAuthor

    Updates to API shape

    1. Reusing CORS policies for trusted origins was an explicit ask from the API review, and ICorsPolicyProvider.GetPolicyAsync is the public extensibility point we need to call. ValueTask<CsrfProtectionResult> is the right return type.
    namespace Microsoft.AspNetCore.Antiforgery;
    
    public interface ICsrfProtection
    {
      ValueTask<CsrfProtectionResult> ValidateAsync(HttpContext context);
    }
    1. Exposing enum is not extensible, so we decided to change to a class-type, which has ways to return same allocated objects which is both cheap and extensible in the future.
    /// <summary>
    /// Represents the result of cross-origin antiforgery request validation.
    /// </summary>
    public sealed class CsrfProtectionResult
    {
        // 
        private static readonly CsrfProtectionResult _allowed = new(isAllowed: true);
        private static readonly CsrfProtectionResult _denied = new(isAllowed: false);
    
        private CsrfProtectionResult(bool isAllowed)
        {
            IsAllowed = isAllowed;
        }
    
        /// <summary>
        /// Gets a value indicating whether the request is allowed.
        /// </summary>
        public bool IsAllowed { get; }
    
        /// <summary>
        /// Returns a <see cref="CsrfProtectionResult"/> indicating the request is allowed.
        /// </summary>
        public static CsrfProtectionResult Allowed() => _allowed;
    
        /// <summary>
        /// Returns a <see cref="CsrfProtectionResult"/> indicating the request is denied.
        /// </summary>
        public static CsrfProtectionResult Denied() => _denied;
    }
  18. DeagleGross commented on May 26, 2026

    @DeagleGross
    MemberAuthor

    Updates to API shape

    1. Reusing CORS policies for trusted origins was an explicit ask from the API review, and ICorsPolicyProvider.GetPolicyAsync is the public extensibility point we need to call. ValueTask<CsrfProtectionResult> is the right return type.
    namespace Microsoft.AspNetCore.Antiforgery;
    
    public interface ICsrfProtection
    {
      ValueTask<CsrfProtectionResult> ValidateAsync(HttpContext context);
    }
    1. Exposing enum is not extensible, so we decided to change to a class-type, which has ways to return same allocated objects which is both cheap and extensible in the future.
    /// <summary>
    /// Represents the result of cross-origin antiforgery request validation.
    /// </summary>
    public sealed class CsrfProtectionResult
    {
        // 
        private static readonly CsrfProtectionResult _allowed = new(isAllowed: true);
        private static readonly CsrfProtectionResult _denied = new(isAllowed: false);
    
        private CsrfProtectionResult(bool isAllowed)
        {
            IsAllowed = isAllowed;
        }
    
        /// <summary>
        /// Gets a value indicating whether the request is allowed.
        /// </summary>
        public bool IsAllowed { get; }
    
        /// <summary>
        /// Returns a <see cref="CsrfProtectionResult"/> indicating the request is allowed.
        /// </summary>
        public static CsrfProtectionResult Allowed() => _allowed;
    
        /// <summary>
        /// Returns a <see cref="CsrfProtectionResult"/> indicating the request is denied.
        /// </summary>
        public static CsrfProtectionResult Denied() => _denied;
    }
  19. locked and limited conversation to collaborators on Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedfeature-antiforgeryon-roadmap

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions