From 4618e25dc92e72d7206fb6863b09667f7ea4f5a2 Mon Sep 17 00:00:00 2001 From: Korolev Dmitry Date: Mon, 19 Jan 2026 14:38:31 +0100 Subject: [PATCH 1/5] init? --- src/Antiforgery/src/AntiforgeryMiddleware.cs | 23 +++++++-- .../AntiforgeryServiceCollectionExtensions.cs | 47 ++++++++++++++++++- .../CrossOriginAntiforgeryOptions.cs | 23 +++++++++ .../CrossOriginValidationResult.cs | 25 ++++++++++ .../CrossOrigin/ICrossOriginAntiforgery.cs | 25 ++++++++++ .../Internal/CrossOriginRequestValidator.cs | 15 ++++++ .../Microsoft.AspNetCore.Antiforgery.csproj | 2 +- 7 files changed, 154 insertions(+), 6 deletions(-) create mode 100644 src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs create mode 100644 src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs create mode 100644 src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs create mode 100644 src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs diff --git a/src/Antiforgery/src/AntiforgeryMiddleware.cs b/src/Antiforgery/src/AntiforgeryMiddleware.cs index 33d79180b698..db5cce1b0ec9 100644 --- a/src/Antiforgery/src/AntiforgeryMiddleware.cs +++ b/src/Antiforgery/src/AntiforgeryMiddleware.cs @@ -1,11 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.AspNetCore.Antiforgery.CrossOrigin; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Antiforgery.Internal; -internal sealed class AntiforgeryMiddleware(IAntiforgery antiforgery, RequestDelegate next) +internal sealed class AntiforgeryMiddleware(ICrossOriginAntiforgery crossOriginAntiforgery, IAntiforgery antiforgery, RequestDelegate next) { private readonly RequestDelegate _next = next; private readonly IAntiforgery _antiforgery = antiforgery; @@ -30,13 +31,28 @@ public Task Invoke(HttpContext context) if (endpoint?.Metadata.GetMetadata() is { RequiresValidation: true }) { - return InvokeAwaited(context); + var crossOriginResult = crossOriginAntiforgery.Validate(context); + + return crossOriginResult switch + { + CrossOriginValidationResult.Allowed => _next(context), + CrossOriginValidationResult.Denied => HandleDenied(context), + CrossOriginValidationResult.Unknown or _ => InvokeTokenValidation(context) + }; } return _next(context); } - public async Task InvokeAwaited(HttpContext context) + private async Task HandleDenied(HttpContext context) + { + // todo change to null + context.Features.Set(new AntiforgeryValidationFeature(isValid: false, exception: null)); + + await _next(context); + } + + private async Task InvokeTokenValidation(HttpContext context) { try { @@ -47,6 +63,7 @@ public async Task InvokeAwaited(HttpContext context) { context.Features.Set(new AntiforgeryValidationFeature(false, e)); } + await _next(context); } } diff --git a/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs b/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs index d40bf9354798..c845794f5832 100644 --- a/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs +++ b/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Antiforgery.CrossOrigin; +using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; @@ -25,9 +27,9 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services services.AddDataProtection(); // Don't overwrite any options setups that a user may have added. - services.TryAddEnumerable( - ServiceDescriptor.Transient, AntiforgeryOptionsSetup>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, AntiforgeryOptionsSetup>()); + // token-based Antiforgery services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); @@ -36,6 +38,9 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services services.TryAddSingleton(); services.TryAddSingleton(); + // cross-origin (sec-fetch-*) Antiforgery + services.TryAddSingleton(); + services.TryAddSingleton>(serviceProvider => { var provider = serviceProvider.GetRequiredService(); @@ -61,4 +66,42 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services services.Configure(setupAction); return services; } + + /// + /// Adds antiforgery services to the specified . + /// + /// The to add services to. + /// An to configure the provided . + /// The so that additional calls can be chained. + public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action setupAction) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(setupAction); + + services.AddAntiforgery(); + services.Configure(setupAction); + return services; + } + + /// + /// Adds antiforgery services to the specified . + /// + /// The to add services to. + /// An to configure the provided . + /// An to configure the provided . + /// The so that additional calls can be chained. + public static IServiceCollection AddAntiforgery(this IServiceCollection services, + Action crossOriginAntiforgeryOptionsSetup, + Action antiforgeryOptionsSetup) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(crossOriginAntiforgeryOptionsSetup); + ArgumentNullException.ThrowIfNull(antiforgeryOptionsSetup); + + services.AddAntiforgery(); + services.Configure(crossOriginAntiforgeryOptionsSetup); + services.Configure(antiforgeryOptionsSetup); + + return services; + } } diff --git a/src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs b/src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs new file mode 100644 index 000000000000..3d316a2948b9 --- /dev/null +++ b/src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin; + +/// +/// Provides programmatic configuration for the cross-origin Antiforgery. +/// +public class CrossOriginAntiforgeryOptions +{ + /// + /// Gets the collection of trusted origins that are allowed for cross-origin requests. + /// Origins should be in the format "scheme://host[:port]" (e.g., "https://example.com"). + /// + public IList TrustedOrigins { get; } = new List(); + + /// + /// Gets or sets whether to fall back to token-based validation when + /// Sec-Fetch-Site and Origin headers are not present. + /// Default is true for backward compatibility. + /// + public bool FallbackToTokenValidation { get; set; } = true; +} diff --git a/src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs b/src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs new file mode 100644 index 000000000000..c14e2eac1383 --- /dev/null +++ b/src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin; + +/// +/// Result of cross-origin request validation. +/// +public enum CrossOriginValidationResult +{ + /// + /// Request is safe (same-origin, trusted, safe method) + /// + Allowed, + + /// + /// Request is cross-origin attack + /// + Denied, + + /// + /// Not enough information to determine the outcome. + /// + Unknown +} diff --git a/src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs b/src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs new file mode 100644 index 000000000000..6be1a4c1dfed --- /dev/null +++ b/src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Http; + +namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin; + +/// +/// Defines a contract for validating cross-origin antiforgery tokens in HTTP requests. +/// +/// Implementations of this interface are responsible for verifying that incoming requests from different +/// origins include valid antiforgery tokens, helping to protect against cross-site request forgery (CSRF) attacks. This +/// interface is typically used in scenarios where cross-origin requests require additional validation beyond standard +/// antiforgery mechanisms. +public interface ICrossOriginAntiforgery +{ + /// + /// Validates the incoming HTTP request against cross-origin antiforgery requirements using the specified options. + /// + /// The HTTP context representing the current request to validate. Cannot be null. + /// The options that configure cross-origin antiforgery validation behavior. Cannot be null. + /// A CrossOriginValidationResult indicating whether the request passed validation and, if not, the reason for + /// failure. + public CrossOriginValidationResult Validate(HttpContext context); +} diff --git a/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs b/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs new file mode 100644 index 000000000000..9c8acd5f37b2 --- /dev/null +++ b/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Antiforgery.CrossOrigin; +using Microsoft.AspNetCore.Http; + +namespace Microsoft.AspNetCore.Antiforgery.Internal; + +internal class CrossOriginRequestValidator : ICrossOriginAntiforgery +{ + public CrossOriginValidationResult Validate(HttpContext context) + { + throw new NotImplementedException(); + } +} diff --git a/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery.csproj b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery.csproj index a70a9e37c045..bbb54b15eec0 100644 --- a/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery.csproj @@ -25,6 +25,6 @@ - + From 54be7b124fa1f3c2176cf89b688b06905cc46875 Mon Sep 17 00:00:00 2001 From: Korolev Dmitry Date: Mon, 19 Jan 2026 14:53:26 +0100 Subject: [PATCH 2/5] implement algo + tests --- .../Internal/CrossOriginRequestValidator.cs | 142 +++++++++++++++++- .../test/AntiforgeryMiddlewareTest.cs | 21 ++- .../CrossOriginAntiforgeryMiddlewareTest.cs | 131 ++++++++++++++++ 3 files changed, 288 insertions(+), 6 deletions(-) create mode 100644 src/Antiforgery/test/CrossOriginAntiforgeryMiddlewareTest.cs diff --git a/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs b/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs index 9c8acd5f37b2..674a1592b07c 100644 --- a/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs +++ b/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs @@ -3,13 +3,151 @@ using Microsoft.AspNetCore.Antiforgery.CrossOrigin; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Antiforgery.Internal; -internal class CrossOriginRequestValidator : ICrossOriginAntiforgery +/// +/// Validates cross-origin requests using Fetch Metadata headers (Sec-Fetch-Site) +/// and Origin header as a fallback, following the algorithm described in +/// https://web.dev/articles/fetch-metadata and Go 1.25's CrossOriginProtection. +/// +internal sealed class CrossOriginRequestValidator : ICrossOriginAntiforgery { + // https://developer.mozilla.org/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site#same-site + private const string SecFetchSiteHeaderName = "Sec-Fetch-Site"; + private const string SecFetchSiteSameOrigin = "same-origin"; + private const string SecFetchSiteNone = "none"; + private const string SecFetchSiteCrossSite = "cross-site"; + private const string SecFetchSiteSameSite = "same-site"; + + private readonly CrossOriginAntiforgeryOptions _options; + + public CrossOriginRequestValidator(IOptions options) + { + _options = options.Value; + } + + /// + /// Validates the incoming HTTP request against cross-origin antiforgery requirements. + /// + /// + /// The algorithm follows these steps: + /// 1. If Origin header matches a trusted origin, allow the request. + /// 2. If Sec-Fetch-Site header is present: + /// - "same-origin" or "none" → allow + /// - "cross-site" or "same-site" → deny + /// 3. If Origin header is present (but not Sec-Fetch-Site): + /// - Compare Origin's host with Host header + /// - Match → allow, No match → deny + /// 4. If neither Sec-Fetch-Site nor Origin is present: + /// - Return Unknown (fallback to token-based validation) + /// public CrossOriginValidationResult Validate(HttpContext context) { - throw new NotImplementedException(); + 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; + } + + /// + /// Checks if the origin is in the trusted origins list. + /// + private bool IsTrustedOrigin(string origin) + { + foreach (var trustedOrigin in _options.TrustedOrigins) + { + if (string.Equals(origin, trustedOrigin, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } + + /// + /// Compares the host portion of the Origin header with the Host header. + /// + /// + /// The Origin header format is: scheme://host[:port] + /// The Host header format is: host[:port] + /// We extract the host (and port if present) from Origin and compare with Host. + /// + private static bool OriginMatchesHost(string origin, string host) + { + if (string.IsNullOrEmpty(host)) + { + return false; + } + + // Parse the Origin to extract host and port + if (!Uri.TryCreate(origin, UriKind.Absolute, out var originUri)) + { + return false; + } + + // Build the host:port string from the Origin URI + var originHost = originUri.IsDefaultPort + ? originUri.Host + : $"{originUri.Host}:{originUri.Port}"; + + // Compare with the Host header (case-insensitive) + return string.Equals(originHost, host, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs b/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs index 2a179c1c40af..b5ffba8fe421 100644 --- a/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs +++ b/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.AspNetCore.Antiforgery.CrossOrigin; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Metadata; using Moq; @@ -17,7 +18,7 @@ public async Task ValidatesAntiforgeryTokenForValidMethods(string method) { var antiforgeryService = new Mock(); antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.FromResult(true)); - var antiforgeryMiddleware = new AntiforgeryMiddleware(antiforgeryService.Object, hc => Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginAntiforgeryThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(); httpContext.Request.Method = method; @@ -31,7 +32,7 @@ public async Task ValidatesAntiforgeryTokenForValidMethods(string method) public async Task RespectsIgnoreAntiforgeryMetadata() { var antiforgeryService = new Mock(); - var antiforgeryMiddleware = new AntiforgeryMiddleware(antiforgeryService.Object, hc => Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginAntiforgeryThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(hasIgnoreMetadata: true); await antiforgeryMiddleware.Invoke(httpContext); @@ -49,7 +50,7 @@ public async Task RespectsIgnoreAntiforgeryMetadata() public async Task IgnoresUnsupportedHttpMethods(string method) { var antiforgeryService = new Mock(); - var antiforgeryMiddleware = new AntiforgeryMiddleware(antiforgeryService.Object, hc => Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginAntiforgeryThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(); httpContext.Request.Method = method; @@ -65,7 +66,7 @@ public async Task SetMiddlewareInvokedProperty(bool hasIgnoreMetadata) { var antiforgeryService = new Mock(); antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.FromResult(true)); - var antiforgeryMiddleware = new AntiforgeryMiddleware(antiforgeryService.Object, hc => Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginAntiforgeryThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(hasIgnoreMetadata); await antiforgeryMiddleware.Invoke(httpContext); @@ -73,6 +74,18 @@ public async Task SetMiddlewareInvokedProperty(bool hasIgnoreMetadata) Assert.True(httpContext.Items.ContainsKey("__AntiforgeryMiddlewareWithEndpointInvoked")); } + /// + /// Creates a mock ICrossOriginAntiforgery that always returns Unknown, + /// which triggers fallback to token-based validation. + /// This simulates the behavior for legacy clients or when cross-origin validation is inconclusive. + /// + private static ICrossOriginAntiforgery CreateCrossOriginAntiforgeryThatReturnsUnknown() + { + var mock = new Mock(); + mock.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); + return mock.Object; + } + internal static DefaultHttpContext GetHttpContext(bool hasIgnoreMetadata = false) { var httpContext = new DefaultHttpContext(); diff --git a/src/Antiforgery/test/CrossOriginAntiforgeryMiddlewareTest.cs b/src/Antiforgery/test/CrossOriginAntiforgeryMiddlewareTest.cs new file mode 100644 index 000000000000..84db8bd2e331 --- /dev/null +++ b/src/Antiforgery/test/CrossOriginAntiforgeryMiddlewareTest.cs @@ -0,0 +1,131 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Antiforgery.CrossOrigin; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Metadata; +using Moq; + +namespace Microsoft.AspNetCore.Antiforgery.Internal; + +public class CrossOriginAntiforgeryMiddlewareTest +{ + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + public async Task AllowsRequestWhenCrossOriginValidationReturnsAllowed(string method) + { + var antiforgeryService = new Mock(); + var crossOriginAntiforgery = new Mock(); + crossOriginAntiforgery.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Allowed); + var nextCalled = false; + var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => + { + nextCalled = true; + return Task.CompletedTask; + }); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + Assert.True(nextCalled); + // Token validation should NOT be called when cross-origin validation allows the request + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + public async Task DeniesRequestWhenCrossOriginValidationReturnsDenied(string method) + { + var antiforgeryService = new Mock(); + var crossOriginAntiforgery = new Mock(); + crossOriginAntiforgery.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Denied); + var nextCalled = false; + var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => + { + nextCalled = true; + return Task.CompletedTask; + }); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + Assert.True(nextCalled); + // Token validation should NOT be called when cross-origin validation denies the request + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + // The validation feature should indicate invalid + Assert.False(httpContext.Features.Get()?.IsValid); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + public async Task FallsBackToTokenValidationWhenCrossOriginValidationReturnsUnknown(string method) + { + var antiforgeryService = new Mock(); + var crossOriginAntiforgery = new Mock(); + crossOriginAntiforgery.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); + antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + // Token validation SHOULD be called when cross-origin validation is unknown + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Once()); + } + + [Theory] + [InlineData("GET")] + [InlineData("HEAD")] + [InlineData("OPTIONS")] + [InlineData("TRACE")] + public async Task DoesNotInvokeCrossOriginValidationForSafeMethods(string method) + { + var antiforgeryService = new Mock(); + var crossOriginAntiforgery = new Mock(); + var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + // Cross-origin validation should NOT be called for safe methods + crossOriginAntiforgery.Verify(c => c.Validate(It.IsAny()), Times.Never()); + // Token validation should also NOT be called for safe methods + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + } + + [Fact] + public async Task DoesNotInvokeCrossOriginValidationWhenEndpointHasIgnoreMetadata() + { + var antiforgeryService = new Mock(); + var crossOriginAntiforgery = new Mock(); + var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(hasIgnoreMetadata: true); + httpContext.Request.Method = "POST"; + + await antiforgeryMiddleware.Invoke(httpContext); + + // Cross-origin validation should NOT be called when endpoint has ignore metadata + crossOriginAntiforgery.Verify(c => c.Validate(It.IsAny()), Times.Never()); + } + + private static DefaultHttpContext GetHttpContext(bool hasIgnoreMetadata = false) + { + var httpContext = new DefaultHttpContext(); + var metadata = !hasIgnoreMetadata + ? new EndpointMetadataCollection(new AntiforgeryMetadata(!hasIgnoreMetadata)) + : new EndpointMetadataCollection(); + httpContext.SetEndpoint(new Endpoint(null, metadata, "TestEndpoint")); + + return httpContext; + } +} From b4e22836a8c6132e9bb780ae7eb334072ad80780 Mon Sep 17 00:00:00 2001 From: Korolev Dmitry Date: Fri, 20 Mar 2026 14:43:15 +0100 Subject: [PATCH 3/5] cross-origin CSRF with Sec-Fetch-Site + UseAntiforgery/UseCrossOriginAntiforgery/UseTokenBasedAntiforgery --- ...AntiforgeryApplicationBuilderExtensions.cs | 46 ++++++++++ src/Antiforgery/src/AntiforgeryMiddleware.cs | 7 +- .../AntiforgeryServiceCollectionExtensions.cs | 86 ++++++++++--------- .../CrossOriginAntiforgeryOptions.cs | 9 +- .../CrossOriginValidationResult.cs | 4 +- .../CrossOrigin/ICrossOriginAntiforgery.cs | 16 ++-- .../src/CrossOriginAntiforgeryMiddleware.cs | 54 ++++++++++++ .../Internal/CrossOriginRequestValidator.cs | 62 +------------ src/Antiforgery/src/PublicAPI.Unshipped.txt | 15 ++++ .../src/TokenBasedAntiforgeryMiddleware.cs | 56 ++++++++++++ ...forgeryApplicationBuilderExtensionsTest.cs | 4 + .../test/AntiforgeryMiddlewareTest.cs | 83 +++++++++++++++--- .../CrossOriginAntiforgeryMiddlewareTest.cs | 75 ++++++---------- 13 files changed, 333 insertions(+), 184 deletions(-) create mode 100644 src/Antiforgery/src/CrossOriginAntiforgeryMiddleware.cs create mode 100644 src/Antiforgery/src/TokenBasedAntiforgeryMiddleware.cs diff --git a/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs b/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs index f7498933e384..9993420a4a1d 100644 --- a/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs +++ b/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Antiforgery.CrossOrigin; using Microsoft.AspNetCore.Antiforgery.Internal; namespace Microsoft.AspNetCore.Builder; @@ -15,6 +16,8 @@ public static class AntiforgeryApplicationBuilderExtensions /// /// Adds the anti-forgery middleware to the pipeline. + /// Uses cross-origin validation (Sec-Fetch-Site / Origin) first, then falls back + /// to token-based validation when cross-origin checks are inconclusive. /// /// The . /// The app builder. @@ -29,6 +32,41 @@ public static IApplicationBuilder UseAntiforgery(this IApplicationBuilder builde return builder; } + /// + /// Adds token-based-only anti-forgery middleware to the pipeline. + /// Cross-origin header checks are skipped. This is the legacy behavior prior to .NET 11. + /// + /// The . + /// The app builder. + public static IApplicationBuilder UseTokenBasedAntiforgery(this IApplicationBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + builder.VerifyAntiforgeryServicesAreRegistered(); + + builder.Properties[AntiforgeryMiddlewareSetKey] = true; + builder.UseMiddleware(); + + return builder; + } + + /// + /// Adds cross-origin-only anti-forgery middleware to the pipeline. + /// Uses Sec-Fetch-Site and Origin headers. Requests where cross-origin validation + /// is inconclusive (e.g., missing headers) are denied. + /// + /// The . + /// The app builder. + public static IApplicationBuilder UseCrossOriginAntiforgery(this IApplicationBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + builder.VerifyCrossOriginAntiforgeryServicesAreRegistered(); + + builder.Properties[AntiforgeryMiddlewareSetKey] = true; + builder.UseMiddleware(); + + return builder; + } + private static void VerifyAntiforgeryServicesAreRegistered(this IApplicationBuilder builder) { if (builder.ApplicationServices.GetService(typeof(IAntiforgery)) == null) @@ -36,4 +74,12 @@ private static void VerifyAntiforgeryServicesAreRegistered(this IApplicationBuil throw new InvalidOperationException("Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddAntiforgery' in the application startup code."); } } + + private static void VerifyCrossOriginAntiforgeryServicesAreRegistered(this IApplicationBuilder builder) + { + if (builder.ApplicationServices.GetService(typeof(ICrossOriginAntiforgery)) == null) + { + throw new InvalidOperationException("Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddCrossOriginAntiforgery' or 'IServiceCollection.AddAntiforgery' in the application startup code."); + } + } } diff --git a/src/Antiforgery/src/AntiforgeryMiddleware.cs b/src/Antiforgery/src/AntiforgeryMiddleware.cs index db5cce1b0ec9..6ba88308967b 100644 --- a/src/Antiforgery/src/AntiforgeryMiddleware.cs +++ b/src/Antiforgery/src/AntiforgeryMiddleware.cs @@ -6,6 +6,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal; +/// +/// Default antiforgery middleware. Performs cross-origin validation first; +/// falls back to token-based validation when the result is inconclusive. +/// internal sealed class AntiforgeryMiddleware(ICrossOriginAntiforgery crossOriginAntiforgery, IAntiforgery antiforgery, RequestDelegate next) { private readonly RequestDelegate _next = next; @@ -46,9 +50,7 @@ public Task Invoke(HttpContext context) private async Task HandleDenied(HttpContext context) { - // todo change to null context.Features.Set(new AntiforgeryValidationFeature(isValid: false, exception: null)); - await _next(context); } @@ -63,7 +65,6 @@ private async Task InvokeTokenValidation(HttpContext context) { context.Features.Set(new AntiforgeryValidationFeature(false, e)); } - await _next(context); } } diff --git a/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs b/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs index c845794f5832..6f1e0cbb838e 100644 --- a/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs +++ b/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Antiforgery.CrossOrigin; using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; namespace Microsoft.Extensions.DependencyInjection; @@ -24,29 +23,7 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services { ArgumentNullException.ThrowIfNull(services); - services.AddDataProtection(); - - // Don't overwrite any options setups that a user may have added. - services.TryAddEnumerable(ServiceDescriptor.Transient, AntiforgeryOptionsSetup>()); - - // token-based Antiforgery - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - - // cross-origin (sec-fetch-*) Antiforgery - services.TryAddSingleton(); - - services.TryAddSingleton>(serviceProvider => - { - var provider = serviceProvider.GetRequiredService(); - var policy = new AntiforgerySerializationContextPooledObjectPolicy(); - return provider.Create(policy); - }); + services.AddAntiforgery((AntiforgeryOptions _) => { }, (CrossOriginAntiforgeryOptions _) => { }); return services; } @@ -56,14 +33,19 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services /// /// The to add services to. /// An to configure the provided . + /// An to configure the provided . /// The so that additional calls can be chained. - public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action setupAction) + public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action setupAction, Action crossOriginSetupAction) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(setupAction); + ArgumentNullException.ThrowIfNull(crossOriginSetupAction); + + services.AddAntiforgery((AntiforgeryOptions _) => { }); // token-based + services.AddCrossOriginAntiforgery((CrossOriginAntiforgeryOptions _) => { }); // cross-origin - services.AddAntiforgery(); services.Configure(setupAction); + services.Configure(crossOriginSetupAction); return services; } @@ -71,37 +53,59 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services /// Adds antiforgery services to the specified . /// /// The to add services to. - /// An to configure the provided . + /// An to configure the provided . /// The so that additional calls can be chained. - public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action setupAction) + public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action setupAction) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(setupAction); - services.AddAntiforgery(); - services.Configure(setupAction); + services.AddDataProtection(); + + // Don't overwrite any options setups that a user may have added. + services.TryAddEnumerable( + ServiceDescriptor.Transient, AntiforgeryOptionsSetup>()); + + // Token-based antiforgery + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + return services; } /// - /// Adds antiforgery services to the specified . + /// Adds cross-origin antiforgery services to the specified . + /// Only registers cross-origin validation; does not register token-based antiforgery or data protection services. /// /// The to add services to. - /// An to configure the provided . - /// An to configure the provided . /// The so that additional calls can be chained. - public static IServiceCollection AddAntiforgery(this IServiceCollection services, - Action crossOriginAntiforgeryOptionsSetup, - Action antiforgeryOptionsSetup) + public static IServiceCollection AddCrossOriginAntiforgery(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); - ArgumentNullException.ThrowIfNull(crossOriginAntiforgeryOptionsSetup); - ArgumentNullException.ThrowIfNull(antiforgeryOptionsSetup); - services.AddAntiforgery(); - services.Configure(crossOriginAntiforgeryOptionsSetup); - services.Configure(antiforgeryOptionsSetup); + services.TryAddSingleton(); + + return services; + } + + /// + /// Adds cross-origin antiforgery services to the specified . + /// Only registers cross-origin validation; does not register token-based antiforgery or data protection services. + /// + /// The to add services to. + /// An to configure the provided . + /// The so that additional calls can be chained. + public static IServiceCollection AddCrossOriginAntiforgery(this IServiceCollection services, Action setupAction) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(setupAction); + services.AddCrossOriginAntiforgery(); + services.Configure(setupAction); return services; } } diff --git a/src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs b/src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs index 3d316a2948b9..aaaecb73bcbd 100644 --- a/src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs +++ b/src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs @@ -4,7 +4,7 @@ namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin; /// -/// Provides programmatic configuration for the cross-origin Antiforgery. +/// Provides programmatic configuration for the cross-origin antiforgery system. /// public class CrossOriginAntiforgeryOptions { @@ -13,11 +13,4 @@ public class CrossOriginAntiforgeryOptions /// Origins should be in the format "scheme://host[:port]" (e.g., "https://example.com"). /// public IList TrustedOrigins { get; } = new List(); - - /// - /// Gets or sets whether to fall back to token-based validation when - /// Sec-Fetch-Site and Origin headers are not present. - /// Default is true for backward compatibility. - /// - public bool FallbackToTokenValidation { get; set; } = true; } diff --git a/src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs b/src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs index c14e2eac1383..f58d9b9258e0 100644 --- a/src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs +++ b/src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs @@ -9,12 +9,12 @@ namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin; public enum CrossOriginValidationResult { /// - /// Request is safe (same-origin, trusted, safe method) + /// Request is safe (same-origin, trusted, safe method). /// Allowed, /// - /// Request is cross-origin attack + /// Request is a cross-origin attack. /// Denied, diff --git a/src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs b/src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs index 6be1a4c1dfed..d18577c14338 100644 --- a/src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs +++ b/src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs @@ -6,20 +6,14 @@ namespace Microsoft.AspNetCore.Antiforgery.CrossOrigin; /// -/// Defines a contract for validating cross-origin antiforgery tokens in HTTP requests. +/// Provides cross-origin request validation using Fetch Metadata headers. /// -/// Implementations of this interface are responsible for verifying that incoming requests from different -/// origins include valid antiforgery tokens, helping to protect against cross-site request forgery (CSRF) attacks. This -/// interface is typically used in scenarios where cross-origin requests require additional validation beyond standard -/// antiforgery mechanisms. public interface ICrossOriginAntiforgery { /// - /// Validates the incoming HTTP request against cross-origin antiforgery requirements using the specified options. + /// Validates the incoming HTTP request against cross-origin antiforgery requirements. /// - /// The HTTP context representing the current request to validate. Cannot be null. - /// The options that configure cross-origin antiforgery validation behavior. Cannot be null. - /// A CrossOriginValidationResult indicating whether the request passed validation and, if not, the reason for - /// failure. - public CrossOriginValidationResult Validate(HttpContext context); + /// The HTTP context representing the current request to validate. + /// A indicating whether the request is allowed, denied, or unknown. + CrossOriginValidationResult Validate(HttpContext context); } diff --git a/src/Antiforgery/src/CrossOriginAntiforgeryMiddleware.cs b/src/Antiforgery/src/CrossOriginAntiforgeryMiddleware.cs new file mode 100644 index 000000000000..6c8be0ced0a4 --- /dev/null +++ b/src/Antiforgery/src/CrossOriginAntiforgeryMiddleware.cs @@ -0,0 +1,54 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Antiforgery.CrossOrigin; +using Microsoft.AspNetCore.Http; + +namespace Microsoft.AspNetCore.Antiforgery.Internal; + +/// +/// Middleware that performs cross-origin-only antiforgery validation. +/// Unknown results are treated as denied (strict mode). +/// +internal sealed class CrossOriginAntiforgeryMiddleware(ICrossOriginAntiforgery crossOriginAntiforgery, RequestDelegate next) +{ + private readonly RequestDelegate _next = next; + + private const string AntiforgeryMiddlewareWithEndpointInvokedKey = "__AntiforgeryMiddlewareWithEndpointInvoked"; + private static readonly object AntiforgeryMiddlewareWithEndpointInvokedValue = new object(); + + public Task Invoke(HttpContext context) + { + var endpoint = context.GetEndpoint(); + + if (endpoint is not null) + { + context.Items[AntiforgeryMiddlewareWithEndpointInvokedKey] = AntiforgeryMiddlewareWithEndpointInvokedValue; + } + + var method = context.Request.Method; + if (!HttpExtensions.IsValidHttpMethodForForm(method)) + { + return _next(context); + } + + if (endpoint?.Metadata.GetMetadata() is { RequiresValidation: true }) + { + var result = crossOriginAntiforgery.Validate(context); + + return result switch + { + CrossOriginValidationResult.Allowed => _next(context), + _ => HandleDenied(context) + }; + } + + return _next(context); + } + + private async Task HandleDenied(HttpContext context) + { + context.Features.Set(new AntiforgeryValidationFeature(isValid: false, exception: null)); + await _next(context); + } +} diff --git a/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs b/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs index 674a1592b07c..d8b4b4bb2c89 100644 --- a/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs +++ b/src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs @@ -9,17 +9,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal; /// /// Validates cross-origin requests using Fetch Metadata headers (Sec-Fetch-Site) -/// and Origin header as a fallback, following the algorithm described in -/// https://web.dev/articles/fetch-metadata and Go 1.25's CrossOriginProtection. +/// and Origin header as a fallback. /// internal sealed class CrossOriginRequestValidator : ICrossOriginAntiforgery { - // https://developer.mozilla.org/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site#same-site private const string SecFetchSiteHeaderName = "Sec-Fetch-Site"; private const string SecFetchSiteSameOrigin = "same-origin"; private const string SecFetchSiteNone = "none"; - private const string SecFetchSiteCrossSite = "cross-site"; - private const string SecFetchSiteSameSite = "same-site"; private readonly CrossOriginAntiforgeryOptions _options; @@ -28,21 +24,6 @@ public CrossOriginRequestValidator(IOptions optio _options = options.Value; } - /// - /// Validates the incoming HTTP request against cross-origin antiforgery requirements. - /// - /// - /// The algorithm follows these steps: - /// 1. If Origin header matches a trusted origin, allow the request. - /// 2. If Sec-Fetch-Site header is present: - /// - "same-origin" or "none" → allow - /// - "cross-site" or "same-site" → deny - /// 3. If Origin header is present (but not Sec-Fetch-Site): - /// - Compare Origin's host with Host header - /// - Match → allow, No match → deny - /// 4. If neither Sec-Fetch-Site nor Origin is present: - /// - Return Unknown (fallback to token-based validation) - /// public CrossOriginValidationResult Validate(HttpContext context) { ArgumentNullException.ThrowIfNull(context); @@ -50,7 +31,6 @@ public CrossOriginValidationResult Validate(HttpContext 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); @@ -64,50 +44,27 @@ public CrossOriginValidationResult Validate(HttpContext context) 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; + return OriginMatchesHost(origin, headers.Host.ToString()) + ? CrossOriginValidationResult.Allowed + : 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; } - /// - /// Checks if the origin is in the trusted origins list. - /// private bool IsTrustedOrigin(string origin) { foreach (var trustedOrigin in _options.TrustedOrigins) @@ -121,14 +78,6 @@ private bool IsTrustedOrigin(string origin) return false; } - /// - /// Compares the host portion of the Origin header with the Host header. - /// - /// - /// The Origin header format is: scheme://host[:port] - /// The Host header format is: host[:port] - /// We extract the host (and port if present) from Origin and compare with Host. - /// private static bool OriginMatchesHost(string origin, string host) { if (string.IsNullOrEmpty(host)) @@ -136,18 +85,15 @@ private static bool OriginMatchesHost(string origin, string host) return false; } - // Parse the Origin to extract host and port if (!Uri.TryCreate(origin, UriKind.Absolute, out var originUri)) { return false; } - // Build the host:port string from the Origin URI var originHost = originUri.IsDefaultPort ? originUri.Host : $"{originUri.Host}:{originUri.Port}"; - // Compare with the Host header (case-insensitive) return string.Equals(originHost, host, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/Antiforgery/src/PublicAPI.Unshipped.txt b/src/Antiforgery/src/PublicAPI.Unshipped.txt index 7dc5c58110bf..bf6633b77b3c 100644 --- a/src/Antiforgery/src/PublicAPI.Unshipped.txt +++ b/src/Antiforgery/src/PublicAPI.Unshipped.txt @@ -1 +1,16 @@ #nullable enable +Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginAntiforgeryOptions +Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginAntiforgeryOptions.CrossOriginAntiforgeryOptions() -> void +Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginAntiforgeryOptions.TrustedOrigins.get -> System.Collections.Generic.IList! +Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult +Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult.Allowed = 0 -> Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult +Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult.Denied = 1 -> Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult +Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult.Unknown = 2 -> Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult +Microsoft.AspNetCore.Antiforgery.CrossOrigin.ICrossOriginAntiforgery +Microsoft.AspNetCore.Antiforgery.CrossOrigin.ICrossOriginAntiforgery.Validate(Microsoft.AspNetCore.Http.HttpContext! context) -> Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult +static Microsoft.AspNetCore.Builder.AntiforgeryApplicationBuilderExtensions.UseCrossOriginAntiforgery(this Microsoft.AspNetCore.Builder.IApplicationBuilder! builder) -> Microsoft.AspNetCore.Builder.IApplicationBuilder! +static Microsoft.AspNetCore.Builder.AntiforgeryApplicationBuilderExtensions.UseTokenBasedAntiforgery(this Microsoft.AspNetCore.Builder.IApplicationBuilder! builder) -> Microsoft.AspNetCore.Builder.IApplicationBuilder! +static Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions.AddAntiforgery(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! setupAction) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions.AddAntiforgery(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! setupAction, System.Action! crossOriginSetupAction) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions.AddCrossOriginAntiforgery(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions.AddCrossOriginAntiforgery(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! setupAction) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! diff --git a/src/Antiforgery/src/TokenBasedAntiforgeryMiddleware.cs b/src/Antiforgery/src/TokenBasedAntiforgeryMiddleware.cs new file mode 100644 index 000000000000..e12d9ebdb3a9 --- /dev/null +++ b/src/Antiforgery/src/TokenBasedAntiforgeryMiddleware.cs @@ -0,0 +1,56 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Http; + +namespace Microsoft.AspNetCore.Antiforgery.Internal; + +/// +/// Middleware that performs token-based-only antiforgery validation. +/// This is the legacy behavior prior to .NET 11. +/// +internal sealed class TokenBasedAntiforgeryMiddleware(IAntiforgery antiforgery, RequestDelegate next) +{ + private readonly RequestDelegate _next = next; + private readonly IAntiforgery _antiforgery = antiforgery; + + private const string AntiforgeryMiddlewareWithEndpointInvokedKey = "__AntiforgeryMiddlewareWithEndpointInvoked"; + private static readonly object AntiforgeryMiddlewareWithEndpointInvokedValue = new object(); + + public Task Invoke(HttpContext context) + { + var endpoint = context.GetEndpoint(); + + if (endpoint is not null) + { + context.Items[AntiforgeryMiddlewareWithEndpointInvokedKey] = AntiforgeryMiddlewareWithEndpointInvokedValue; + } + + var method = context.Request.Method; + if (!HttpExtensions.IsValidHttpMethodForForm(method)) + { + return _next(context); + } + + if (endpoint?.Metadata.GetMetadata() is { RequiresValidation: true }) + { + return InvokeTokenValidation(context); + } + + return _next(context); + } + + private async Task InvokeTokenValidation(HttpContext context) + { + try + { + await _antiforgery.ValidateRequestAsync(context); + context.Features.Set(AntiforgeryValidationFeature.Valid); + } + catch (AntiforgeryValidationException e) + { + context.Features.Set(new AntiforgeryValidationFeature(false, e)); + } + await _next(context); + } +} diff --git a/src/Antiforgery/test/AntiforgeryApplicationBuilderExtensionsTest.cs b/src/Antiforgery/test/AntiforgeryApplicationBuilderExtensionsTest.cs index 81303a317bd2..485099e3abec 100644 --- a/src/Antiforgery/test/AntiforgeryApplicationBuilderExtensionsTest.cs +++ b/src/Antiforgery/test/AntiforgeryApplicationBuilderExtensionsTest.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.AspNetCore.Antiforgery.CrossOrigin; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -53,6 +54,9 @@ private IServiceProvider CreateServices(IAntiforgery? antiforgeryService = null) if (antiforgeryService is not null) { services.AddSingleton(antiforgeryService); + var crossOriginMock = new Mock(); + crossOriginMock.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); + services.AddSingleton(crossOriginMock.Object); } var serviceProvider = services.BuildServiceProvider(); return serviceProvider; diff --git a/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs b/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs index b5ffba8fe421..edc0ec355647 100644 --- a/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs +++ b/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs @@ -18,13 +18,13 @@ public async Task ValidatesAntiforgeryTokenForValidMethods(string method) { var antiforgeryService = new Mock(); antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.FromResult(true)); - var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginAntiforgeryThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(); httpContext.Request.Method = method; await antiforgeryMiddleware.Invoke(httpContext); - antiforgeryService.Verify(antiforgeryService => antiforgeryService.ValidateRequestAsync(httpContext), Times.AtMostOnce()); + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.AtMostOnce()); Assert.True(httpContext.Features.Get()?.IsValid); } @@ -32,12 +32,12 @@ public async Task ValidatesAntiforgeryTokenForValidMethods(string method) public async Task RespectsIgnoreAntiforgeryMetadata() { var antiforgeryService = new Mock(); - var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginAntiforgeryThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(hasIgnoreMetadata: true); await antiforgeryMiddleware.Invoke(httpContext); - antiforgeryService.Verify(antiforgeryService => antiforgeryService.ValidateRequestAsync(httpContext), Times.Never()); + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); } [Theory] @@ -50,13 +50,13 @@ public async Task RespectsIgnoreAntiforgeryMetadata() public async Task IgnoresUnsupportedHttpMethods(string method) { var antiforgeryService = new Mock(); - var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginAntiforgeryThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(); httpContext.Request.Method = method; await antiforgeryMiddleware.Invoke(httpContext); - antiforgeryService.Verify(antiforgeryService => antiforgeryService.ValidateRequestAsync(httpContext), Times.Never()); + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); } [Theory] @@ -66,7 +66,7 @@ public async Task SetMiddlewareInvokedProperty(bool hasIgnoreMetadata) { var antiforgeryService = new Mock(); antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.FromResult(true)); - var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginAntiforgeryThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); + var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(hasIgnoreMetadata); await antiforgeryMiddleware.Invoke(httpContext); @@ -74,12 +74,69 @@ public async Task SetMiddlewareInvokedProperty(bool hasIgnoreMetadata) Assert.True(httpContext.Items.ContainsKey("__AntiforgeryMiddlewareWithEndpointInvoked")); } - /// - /// Creates a mock ICrossOriginAntiforgery that always returns Unknown, - /// which triggers fallback to token-based validation. - /// This simulates the behavior for legacy clients or when cross-origin validation is inconclusive. - /// - private static ICrossOriginAntiforgery CreateCrossOriginAntiforgeryThatReturnsUnknown() + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + public async Task SkipsTokenValidation_WhenCrossOriginAllows(string method) + { + var antiforgeryService = new Mock(); + var crossOrigin = new Mock(); + crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Allowed); + var nextCalled = false; + var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOrigin.Object, antiforgeryService.Object, hc => + { + nextCalled = true; + return Task.CompletedTask; + }); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + Assert.True(nextCalled); + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + public async Task DeniesRequest_WhenCrossOriginDenies(string method) + { + var antiforgeryService = new Mock(); + var crossOrigin = new Mock(); + crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Denied); + var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOrigin.Object, antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + Assert.False(httpContext.Features.Get()?.IsValid); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + public async Task FallsBackToToken_WhenCrossOriginUnknown(string method) + { + var antiforgeryService = new Mock(); + antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.CompletedTask); + var crossOrigin = new Mock(); + crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); + var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOrigin.Object, antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Once()); + } + + private static ICrossOriginAntiforgery CreateCrossOriginThatReturnsUnknown() { var mock = new Mock(); mock.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); diff --git a/src/Antiforgery/test/CrossOriginAntiforgeryMiddlewareTest.cs b/src/Antiforgery/test/CrossOriginAntiforgeryMiddlewareTest.cs index 84db8bd2e331..3fd3e3068f95 100644 --- a/src/Antiforgery/test/CrossOriginAntiforgeryMiddlewareTest.cs +++ b/src/Antiforgery/test/CrossOriginAntiforgeryMiddlewareTest.cs @@ -14,13 +14,12 @@ public class CrossOriginAntiforgeryMiddlewareTest [InlineData("POST")] [InlineData("PUT")] [InlineData("PATCH")] - public async Task AllowsRequestWhenCrossOriginValidationReturnsAllowed(string method) + public async Task AllowsRequest_WhenCrossOriginReturnsAllowed(string method) { - var antiforgeryService = new Mock(); - var crossOriginAntiforgery = new Mock(); - crossOriginAntiforgery.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Allowed); + var crossOrigin = new Mock(); + crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Allowed); var nextCalled = false; - var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => + var middleware = new CrossOriginAntiforgeryMiddleware(crossOrigin.Object, hc => { nextCalled = true; return Task.CompletedTask; @@ -28,37 +27,26 @@ public async Task AllowsRequestWhenCrossOriginValidationReturnsAllowed(string me var httpContext = GetHttpContext(); httpContext.Request.Method = method; - await antiforgeryMiddleware.Invoke(httpContext); + await middleware.Invoke(httpContext); Assert.True(nextCalled); - // Token validation should NOT be called when cross-origin validation allows the request - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + Assert.Null(httpContext.Features.Get()); } [Theory] [InlineData("POST")] [InlineData("PUT")] [InlineData("PATCH")] - public async Task DeniesRequestWhenCrossOriginValidationReturnsDenied(string method) + public async Task DeniesRequest_WhenCrossOriginReturnsDenied(string method) { - var antiforgeryService = new Mock(); - var crossOriginAntiforgery = new Mock(); - crossOriginAntiforgery.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Denied); - var nextCalled = false; - var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => - { - nextCalled = true; - return Task.CompletedTask; - }); + var crossOrigin = new Mock(); + crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Denied); + var middleware = new CrossOriginAntiforgeryMiddleware(crossOrigin.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(); httpContext.Request.Method = method; - await antiforgeryMiddleware.Invoke(httpContext); + await middleware.Invoke(httpContext); - Assert.True(nextCalled); - // Token validation should NOT be called when cross-origin validation denies the request - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); - // The validation feature should indicate invalid Assert.False(httpContext.Features.Get()?.IsValid); } @@ -66,20 +54,17 @@ public async Task DeniesRequestWhenCrossOriginValidationReturnsDenied(string met [InlineData("POST")] [InlineData("PUT")] [InlineData("PATCH")] - public async Task FallsBackToTokenValidationWhenCrossOriginValidationReturnsUnknown(string method) + public async Task DeniesRequest_WhenCrossOriginReturnsUnknown(string method) { - var antiforgeryService = new Mock(); - var crossOriginAntiforgery = new Mock(); - crossOriginAntiforgery.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); - antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.CompletedTask); - var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => Task.CompletedTask); + var crossOrigin = new Mock(); + crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); + var middleware = new CrossOriginAntiforgeryMiddleware(crossOrigin.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(); httpContext.Request.Method = method; - await antiforgeryMiddleware.Invoke(httpContext); + await middleware.Invoke(httpContext); - // Token validation SHOULD be called when cross-origin validation is unknown - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Once()); + Assert.False(httpContext.Features.Get()?.IsValid); } [Theory] @@ -87,35 +72,29 @@ public async Task FallsBackToTokenValidationWhenCrossOriginValidationReturnsUnkn [InlineData("HEAD")] [InlineData("OPTIONS")] [InlineData("TRACE")] - public async Task DoesNotInvokeCrossOriginValidationForSafeMethods(string method) + public async Task SkipsValidation_ForSafeMethods(string method) { - var antiforgeryService = new Mock(); - var crossOriginAntiforgery = new Mock(); - var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => Task.CompletedTask); + var crossOrigin = new Mock(); + var middleware = new CrossOriginAntiforgeryMiddleware(crossOrigin.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(); httpContext.Request.Method = method; - await antiforgeryMiddleware.Invoke(httpContext); + await middleware.Invoke(httpContext); - // Cross-origin validation should NOT be called for safe methods - crossOriginAntiforgery.Verify(c => c.Validate(It.IsAny()), Times.Never()); - // Token validation should also NOT be called for safe methods - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + crossOrigin.Verify(c => c.Validate(It.IsAny()), Times.Never()); } [Fact] - public async Task DoesNotInvokeCrossOriginValidationWhenEndpointHasIgnoreMetadata() + public async Task SkipsValidation_WhenEndpointHasIgnoreMetadata() { - var antiforgeryService = new Mock(); - var crossOriginAntiforgery = new Mock(); - var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOriginAntiforgery.Object, antiforgeryService.Object, hc => Task.CompletedTask); + var crossOrigin = new Mock(); + var middleware = new CrossOriginAntiforgeryMiddleware(crossOrigin.Object, hc => Task.CompletedTask); var httpContext = GetHttpContext(hasIgnoreMetadata: true); httpContext.Request.Method = "POST"; - await antiforgeryMiddleware.Invoke(httpContext); + await middleware.Invoke(httpContext); - // Cross-origin validation should NOT be called when endpoint has ignore metadata - crossOriginAntiforgery.Verify(c => c.Validate(It.IsAny()), Times.Never()); + crossOrigin.Verify(c => c.Validate(It.IsAny()), Times.Never()); } private static DefaultHttpContext GetHttpContext(bool hasIgnoreMetadata = false) From 83ef3ddbeac36c293dc0309d423194be601d96b5 Mon Sep 17 00:00:00 2001 From: Korolev Dmitry Date: Fri, 20 Mar 2026 14:51:56 +0100 Subject: [PATCH 4/5] cleanup --- ...AntiforgeryApplicationBuilderExtensions.cs | 2 +- src/Antiforgery/src/AntiforgeryMiddleware.cs | 70 -------- src/Antiforgery/src/PublicAPI.Unshipped.txt | 1 - .../src/TokenBasedAntiforgeryMiddleware.cs | 1 - ...forgeryApplicationBuilderExtensionsTest.cs | 2 +- .../test/AntiforgeryMiddlewareTest.cs | 156 ------------------ .../TokenBasedAntiforgeryMiddlewareTest.cs | 86 ++++++++++ 7 files changed, 88 insertions(+), 230 deletions(-) delete mode 100644 src/Antiforgery/src/AntiforgeryMiddleware.cs delete mode 100644 src/Antiforgery/test/AntiforgeryMiddlewareTest.cs create mode 100644 src/Antiforgery/test/TokenBasedAntiforgeryMiddlewareTest.cs diff --git a/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs b/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs index 9993420a4a1d..b2f1e3bbb418 100644 --- a/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs +++ b/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs @@ -27,7 +27,7 @@ public static IApplicationBuilder UseAntiforgery(this IApplicationBuilder builde builder.VerifyAntiforgeryServicesAreRegistered(); builder.Properties[AntiforgeryMiddlewareSetKey] = true; - builder.UseMiddleware(); + builder.UseMiddleware(); return builder; } diff --git a/src/Antiforgery/src/AntiforgeryMiddleware.cs b/src/Antiforgery/src/AntiforgeryMiddleware.cs deleted file mode 100644 index 6ba88308967b..000000000000 --- a/src/Antiforgery/src/AntiforgeryMiddleware.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Microsoft.AspNetCore.Antiforgery.CrossOrigin; -using Microsoft.AspNetCore.Http; - -namespace Microsoft.AspNetCore.Antiforgery.Internal; - -/// -/// Default antiforgery middleware. Performs cross-origin validation first; -/// falls back to token-based validation when the result is inconclusive. -/// -internal sealed class AntiforgeryMiddleware(ICrossOriginAntiforgery crossOriginAntiforgery, IAntiforgery antiforgery, RequestDelegate next) -{ - private readonly RequestDelegate _next = next; - private readonly IAntiforgery _antiforgery = antiforgery; - - private const string AntiforgeryMiddlewareWithEndpointInvokedKey = "__AntiforgeryMiddlewareWithEndpointInvoked"; - private static readonly object AntiforgeryMiddlewareWithEndpointInvokedValue = new object(); - - public Task Invoke(HttpContext context) - { - var endpoint = context.GetEndpoint(); - - if (endpoint is not null) - { - context.Items[AntiforgeryMiddlewareWithEndpointInvokedKey] = AntiforgeryMiddlewareWithEndpointInvokedValue; - } - - var method = context.Request.Method; - if (!HttpExtensions.IsValidHttpMethodForForm(method)) - { - return _next(context); - } - - if (endpoint?.Metadata.GetMetadata() is { RequiresValidation: true }) - { - var crossOriginResult = crossOriginAntiforgery.Validate(context); - - return crossOriginResult switch - { - CrossOriginValidationResult.Allowed => _next(context), - CrossOriginValidationResult.Denied => HandleDenied(context), - CrossOriginValidationResult.Unknown or _ => InvokeTokenValidation(context) - }; - } - - return _next(context); - } - - private async Task HandleDenied(HttpContext context) - { - context.Features.Set(new AntiforgeryValidationFeature(isValid: false, exception: null)); - await _next(context); - } - - private async Task InvokeTokenValidation(HttpContext context) - { - try - { - await _antiforgery.ValidateRequestAsync(context); - context.Features.Set(AntiforgeryValidationFeature.Valid); - } - catch (AntiforgeryValidationException e) - { - context.Features.Set(new AntiforgeryValidationFeature(false, e)); - } - await _next(context); - } -} diff --git a/src/Antiforgery/src/PublicAPI.Unshipped.txt b/src/Antiforgery/src/PublicAPI.Unshipped.txt index bf6633b77b3c..948b305f0264 100644 --- a/src/Antiforgery/src/PublicAPI.Unshipped.txt +++ b/src/Antiforgery/src/PublicAPI.Unshipped.txt @@ -10,7 +10,6 @@ Microsoft.AspNetCore.Antiforgery.CrossOrigin.ICrossOriginAntiforgery Microsoft.AspNetCore.Antiforgery.CrossOrigin.ICrossOriginAntiforgery.Validate(Microsoft.AspNetCore.Http.HttpContext! context) -> Microsoft.AspNetCore.Antiforgery.CrossOrigin.CrossOriginValidationResult static Microsoft.AspNetCore.Builder.AntiforgeryApplicationBuilderExtensions.UseCrossOriginAntiforgery(this Microsoft.AspNetCore.Builder.IApplicationBuilder! builder) -> Microsoft.AspNetCore.Builder.IApplicationBuilder! static Microsoft.AspNetCore.Builder.AntiforgeryApplicationBuilderExtensions.UseTokenBasedAntiforgery(this Microsoft.AspNetCore.Builder.IApplicationBuilder! builder) -> Microsoft.AspNetCore.Builder.IApplicationBuilder! -static Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions.AddAntiforgery(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! setupAction) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions.AddAntiforgery(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! setupAction, System.Action! crossOriginSetupAction) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions.AddCrossOriginAntiforgery(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions.AddCrossOriginAntiforgery(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! setupAction) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! diff --git a/src/Antiforgery/src/TokenBasedAntiforgeryMiddleware.cs b/src/Antiforgery/src/TokenBasedAntiforgeryMiddleware.cs index e12d9ebdb3a9..cfcd01b2facb 100644 --- a/src/Antiforgery/src/TokenBasedAntiforgeryMiddleware.cs +++ b/src/Antiforgery/src/TokenBasedAntiforgeryMiddleware.cs @@ -7,7 +7,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal; /// /// Middleware that performs token-based-only antiforgery validation. -/// This is the legacy behavior prior to .NET 11. /// internal sealed class TokenBasedAntiforgeryMiddleware(IAntiforgery antiforgery, RequestDelegate next) { diff --git a/src/Antiforgery/test/AntiforgeryApplicationBuilderExtensionsTest.cs b/src/Antiforgery/test/AntiforgeryApplicationBuilderExtensionsTest.cs index 485099e3abec..c6b2506413f6 100644 --- a/src/Antiforgery/test/AntiforgeryApplicationBuilderExtensionsTest.cs +++ b/src/Antiforgery/test/AntiforgeryApplicationBuilderExtensionsTest.cs @@ -17,7 +17,7 @@ public async Task UseAntiforgery_HasRequiredServices_RegistersMiddleware() var antiforgeryService = new Mock(); var services = CreateServices(antiforgeryService.Object); var builder = new ApplicationBuilder(services); - var httpContext = AntiforgeryMiddlewareTest.GetHttpContext(); + var httpContext = TokenBasedAntiforgeryMiddlewareTest.GetHttpContext(); Assert.False(builder.Properties.ContainsKey("__AntiforgeryMiddlewareSet")); diff --git a/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs b/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs deleted file mode 100644 index edc0ec355647..000000000000 --- a/src/Antiforgery/test/AntiforgeryMiddlewareTest.cs +++ /dev/null @@ -1,156 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Microsoft.AspNetCore.Antiforgery.CrossOrigin; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Metadata; -using Moq; - -namespace Microsoft.AspNetCore.Antiforgery.Internal; - -public class AntiforgeryMiddlewareTest -{ - [Theory] - [InlineData("POST")] - [InlineData("PUT")] - [InlineData("PATCH")] - public async Task ValidatesAntiforgeryTokenForValidMethods(string method) - { - var antiforgeryService = new Mock(); - antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.FromResult(true)); - var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); - var httpContext = GetHttpContext(); - httpContext.Request.Method = method; - - await antiforgeryMiddleware.Invoke(httpContext); - - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.AtMostOnce()); - Assert.True(httpContext.Features.Get()?.IsValid); - } - - [Fact] - public async Task RespectsIgnoreAntiforgeryMetadata() - { - var antiforgeryService = new Mock(); - var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); - var httpContext = GetHttpContext(hasIgnoreMetadata: true); - - await antiforgeryMiddleware.Invoke(httpContext); - - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); - } - - [Theory] - [InlineData("GET")] - [InlineData("TRACE")] - [InlineData("HEAD")] - [InlineData("OPTIONS")] - [InlineData("DELETE")] - [InlineData("CONNECT")] - public async Task IgnoresUnsupportedHttpMethods(string method) - { - var antiforgeryService = new Mock(); - var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); - var httpContext = GetHttpContext(); - httpContext.Request.Method = method; - - await antiforgeryMiddleware.Invoke(httpContext); - - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task SetMiddlewareInvokedProperty(bool hasIgnoreMetadata) - { - var antiforgeryService = new Mock(); - antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.FromResult(true)); - var antiforgeryMiddleware = new AntiforgeryMiddleware(CreateCrossOriginThatReturnsUnknown(), antiforgeryService.Object, hc => Task.CompletedTask); - var httpContext = GetHttpContext(hasIgnoreMetadata); - - await antiforgeryMiddleware.Invoke(httpContext); - - Assert.True(httpContext.Items.ContainsKey("__AntiforgeryMiddlewareWithEndpointInvoked")); - } - - [Theory] - [InlineData("POST")] - [InlineData("PUT")] - [InlineData("PATCH")] - public async Task SkipsTokenValidation_WhenCrossOriginAllows(string method) - { - var antiforgeryService = new Mock(); - var crossOrigin = new Mock(); - crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Allowed); - var nextCalled = false; - var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOrigin.Object, antiforgeryService.Object, hc => - { - nextCalled = true; - return Task.CompletedTask; - }); - var httpContext = GetHttpContext(); - httpContext.Request.Method = method; - - await antiforgeryMiddleware.Invoke(httpContext); - - Assert.True(nextCalled); - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); - } - - [Theory] - [InlineData("POST")] - [InlineData("PUT")] - [InlineData("PATCH")] - public async Task DeniesRequest_WhenCrossOriginDenies(string method) - { - var antiforgeryService = new Mock(); - var crossOrigin = new Mock(); - crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Denied); - var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOrigin.Object, antiforgeryService.Object, hc => Task.CompletedTask); - var httpContext = GetHttpContext(); - httpContext.Request.Method = method; - - await antiforgeryMiddleware.Invoke(httpContext); - - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); - Assert.False(httpContext.Features.Get()?.IsValid); - } - - [Theory] - [InlineData("POST")] - [InlineData("PUT")] - [InlineData("PATCH")] - public async Task FallsBackToToken_WhenCrossOriginUnknown(string method) - { - var antiforgeryService = new Mock(); - antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.CompletedTask); - var crossOrigin = new Mock(); - crossOrigin.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); - var antiforgeryMiddleware = new AntiforgeryMiddleware(crossOrigin.Object, antiforgeryService.Object, hc => Task.CompletedTask); - var httpContext = GetHttpContext(); - httpContext.Request.Method = method; - - await antiforgeryMiddleware.Invoke(httpContext); - - antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Once()); - } - - private static ICrossOriginAntiforgery CreateCrossOriginThatReturnsUnknown() - { - var mock = new Mock(); - mock.Setup(c => c.Validate(It.IsAny())).Returns(CrossOriginValidationResult.Unknown); - return mock.Object; - } - - internal static DefaultHttpContext GetHttpContext(bool hasIgnoreMetadata = false) - { - var httpContext = new DefaultHttpContext(); - var metadata = !hasIgnoreMetadata - ? new EndpointMetadataCollection(new AntiforgeryMetadata(!hasIgnoreMetadata)) - : new EndpointMetadataCollection(); - httpContext.SetEndpoint(new Endpoint(null, metadata, "TestEndpoint")); - - return httpContext; - } -} diff --git a/src/Antiforgery/test/TokenBasedAntiforgeryMiddlewareTest.cs b/src/Antiforgery/test/TokenBasedAntiforgeryMiddlewareTest.cs new file mode 100644 index 000000000000..072e58748dfe --- /dev/null +++ b/src/Antiforgery/test/TokenBasedAntiforgeryMiddlewareTest.cs @@ -0,0 +1,86 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Metadata; +using Moq; + +namespace Microsoft.AspNetCore.Antiforgery.Internal; + +public class TokenBasedAntiforgeryMiddlewareTest +{ + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + public async Task ValidatesAntiforgeryTokenForValidMethods(string method) + { + var antiforgeryService = new Mock(); + antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.FromResult(true)); + var antiforgeryMiddleware = new TokenBasedAntiforgeryMiddleware(antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.AtMostOnce()); + Assert.True(httpContext.Features.Get()?.IsValid); + } + + [Fact] + public async Task RespectsIgnoreAntiforgeryMetadata() + { + var antiforgeryService = new Mock(); + var antiforgeryMiddleware = new TokenBasedAntiforgeryMiddleware(antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(hasIgnoreMetadata: true); + + await antiforgeryMiddleware.Invoke(httpContext); + + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + } + + [Theory] + [InlineData("GET")] + [InlineData("TRACE")] + [InlineData("HEAD")] + [InlineData("OPTIONS")] + [InlineData("DELETE")] + [InlineData("CONNECT")] + public async Task IgnoresUnsupportedHttpMethods(string method) + { + var antiforgeryService = new Mock(); + var antiforgeryMiddleware = new TokenBasedAntiforgeryMiddleware(antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(); + httpContext.Request.Method = method; + + await antiforgeryMiddleware.Invoke(httpContext); + + antiforgeryService.Verify(af => af.ValidateRequestAsync(httpContext), Times.Never()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SetMiddlewareInvokedProperty(bool hasIgnoreMetadata) + { + var antiforgeryService = new Mock(); + antiforgeryService.Setup(af => af.ValidateRequestAsync(It.IsAny())).Returns(Task.FromResult(true)); + var antiforgeryMiddleware = new TokenBasedAntiforgeryMiddleware(antiforgeryService.Object, hc => Task.CompletedTask); + var httpContext = GetHttpContext(hasIgnoreMetadata); + + await antiforgeryMiddleware.Invoke(httpContext); + + Assert.True(httpContext.Items.ContainsKey("__AntiforgeryMiddlewareWithEndpointInvoked")); + } + + internal static DefaultHttpContext GetHttpContext(bool hasIgnoreMetadata = false) + { + var httpContext = new DefaultHttpContext(); + var metadata = !hasIgnoreMetadata + ? new EndpointMetadataCollection(new AntiforgeryMetadata(!hasIgnoreMetadata)) + : new EndpointMetadataCollection(); + httpContext.SetEndpoint(new Endpoint(null, metadata, "TestEndpoint")); + + return httpContext; + } +} From f86262af6b5a463b544dfc6ef5b12a316d143724 Mon Sep 17 00:00:00 2001 From: Korolev Dmitry Date: Fri, 20 Mar 2026 14:55:39 +0100 Subject: [PATCH 5/5] fix confl --- src/submodules/googletest | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/submodules/googletest b/src/submodules/googletest index 94be250af7e1..cb1bd881919a 160000 --- a/src/submodules/googletest +++ b/src/submodules/googletest @@ -1 +1 @@ -Subproject commit 94be250af7e14c58dcbf476972d2d7141551ff67 +Subproject commit cb1bd881919af685667b8f77a1d4484b04b13a56