Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -15,6 +16,8 @@ public static class AntiforgeryApplicationBuilderExtensions

/// <summary>
/// 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.
/// </summary>
/// <param name="builder">The <see cref="IApplicationBuilder"/>.</param>
/// <returns>The app builder.</returns>
Expand All @@ -24,7 +27,42 @@ public static IApplicationBuilder UseAntiforgery(this IApplicationBuilder builde
builder.VerifyAntiforgeryServicesAreRegistered();

builder.Properties[AntiforgeryMiddlewareSetKey] = true;
builder.UseMiddleware<AntiforgeryMiddleware>();
builder.UseMiddleware<TokenBasedAntiforgeryMiddleware>();

return builder;
}

/// <summary>
/// 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.
/// </summary>
/// <param name="builder">The <see cref="IApplicationBuilder"/>.</param>
/// <returns>The app builder.</returns>
public static IApplicationBuilder UseTokenBasedAntiforgery(this IApplicationBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.VerifyAntiforgeryServicesAreRegistered();

Comment on lines +41 to +45

Copilot AI Mar 20, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UseAntiforgery() still only checks for IAntiforgery, but AntiforgeryMiddleware now also depends on ICrossOriginAntiforgery. Consider updating the UseAntiforgery() verification logic (similar to VerifyCrossOriginAntiforgeryServicesAreRegistered) so the error is thrown at pipeline setup time with an actionable message.

Copilot uses AI. Check for mistakes.
builder.Properties[AntiforgeryMiddlewareSetKey] = true;
builder.UseMiddleware<TokenBasedAntiforgeryMiddleware>();

return builder;
}

/// <summary>
/// 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.
/// </summary>
/// <param name="builder">The <see cref="IApplicationBuilder"/>.</param>
/// <returns>The app builder.</returns>
public static IApplicationBuilder UseCrossOriginAntiforgery(this IApplicationBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.VerifyCrossOriginAntiforgeryServicesAreRegistered();

builder.Properties[AntiforgeryMiddlewareSetKey] = true;
builder.UseMiddleware<CrossOriginAntiforgeryMiddleware>();

return builder;
}
Expand All @@ -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.");
}
}
}
64 changes: 60 additions & 4 deletions src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.Options;

Expand All @@ -21,12 +23,50 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services
{
ArgumentNullException.ThrowIfNull(services);

services.AddAntiforgery((AntiforgeryOptions _) => { }, (CrossOriginAntiforgeryOptions _) => { });

return services;
}

/// <summary>
/// Adds antiforgery services to the specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="setupAction">An <see cref="Action{AntiforgeryOptions}"/> to configure the provided <see cref="AntiforgeryOptions"/>.</param>
/// <param name="crossOriginSetupAction">An <see cref="Action{CrossOriginAntiforgeryOptions}"/> to configure the provided <see cref="CrossOriginAntiforgeryOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action<AntiforgeryOptions> setupAction, Action<CrossOriginAntiforgeryOptions> crossOriginSetupAction)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(setupAction);
ArgumentNullException.ThrowIfNull(crossOriginSetupAction);

services.AddAntiforgery((AntiforgeryOptions _) => { }); // token-based
services.AddCrossOriginAntiforgery((CrossOriginAntiforgeryOptions _) => { }); // cross-origin

services.Configure(setupAction);
services.Configure(crossOriginSetupAction);
return services;
}

/// <summary>
/// Adds antiforgery services to the specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="setupAction">An <see cref="Action{AntiforgeryOptions}"/> to configure the provided <see cref="AntiforgeryOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action<AntiforgeryOptions> setupAction)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(setupAction);

services.AddDataProtection();

// Don't overwrite any options setups that a user may have added.
services.TryAddEnumerable(
Comment on lines +58 to 66

Copilot AI Mar 20, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The common overload AddAntiforgery(Action) does not register ICrossOriginAntiforgery, but AntiforgeryMiddleware now requires it in the constructor. Apps using the existing AddAntiforgery(options => ...) + UseAntiforgery() pattern will fail at runtime; this overload should also register the cross-origin services (or UseAntiforgery should fall back to a token-only middleware when cross-origin services are absent).

Copilot uses AI. Check for mistakes.
ServiceDescriptor.Transient<IConfigureOptions<AntiforgeryOptions>, AntiforgeryOptionsSetup>());

// Token-based antiforgery
services.TryAddSingleton<IAntiforgery, DefaultAntiforgery>();
services.TryAddSingleton<IAntiforgeryTokenGenerator, DefaultAntiforgeryTokenGenerator>();
services.TryAddSingleton<IAntiforgeryTokenSerializer, DefaultAntiforgeryTokenSerializer>();
Expand All @@ -38,17 +78,33 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services
}

/// <summary>
/// Adds antiforgery services to the specified <see cref="IServiceCollection" />.
/// Adds cross-origin antiforgery services to the specified <see cref="IServiceCollection" />.
/// Only registers cross-origin validation; does not register token-based antiforgery or data protection services.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="setupAction">An <see cref="Action{AntiforgeryOptions}"/> to configure the provided <see cref="AntiforgeryOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action<AntiforgeryOptions> setupAction)
public static IServiceCollection AddCrossOriginAntiforgery(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);

Copilot AI Mar 20, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AddCrossOriginAntiforgery() registers CrossOriginRequestValidator, which requires IOptions. If a consumer only calls AddCrossOriginAntiforgery() (without other features that add Options), DI may fail to resolve IOptions<...>; consider ensuring Options services are added here (e.g., services.AddOptions()) to make this registration self-contained.

Suggested change
services.AddOptions();

Copilot uses AI. Check for mistakes.
services.TryAddSingleton<ICrossOriginAntiforgery, CrossOriginRequestValidator>();

return services;
}

/// <summary>
/// Adds cross-origin antiforgery services to the specified <see cref="IServiceCollection" />.
/// Only registers cross-origin validation; does not register token-based antiforgery or data protection services.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="setupAction">An <see cref="Action{CrossOriginAntiforgeryOptions}"/> to configure the provided <see cref="CrossOriginAntiforgeryOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddCrossOriginAntiforgery(this IServiceCollection services, Action<CrossOriginAntiforgeryOptions> setupAction)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(setupAction);

services.AddAntiforgery();
services.AddCrossOriginAntiforgery();
services.Configure(setupAction);
return services;
}
Expand Down
16 changes: 16 additions & 0 deletions src/Antiforgery/src/CrossOrigin/CrossOriginAntiforgeryOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// 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;

/// <summary>
/// Provides programmatic configuration for the cross-origin antiforgery system.
/// </summary>
public class CrossOriginAntiforgeryOptions
{
/// <summary>
/// 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").
/// </summary>
public IList<string> TrustedOrigins { get; } = new List<string>();
}
25 changes: 25 additions & 0 deletions src/Antiforgery/src/CrossOrigin/CrossOriginValidationResult.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Result of cross-origin request validation.
/// </summary>
public enum CrossOriginValidationResult
{
/// <summary>
/// Request is safe (same-origin, trusted, safe method).
/// </summary>
Allowed,

/// <summary>
/// Request is a cross-origin attack.
/// </summary>
Denied,

/// <summary>
/// Not enough information to determine the outcome.
/// </summary>
Unknown
}
19 changes: 19 additions & 0 deletions src/Antiforgery/src/CrossOrigin/ICrossOriginAntiforgery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// 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;

/// <summary>
/// Provides cross-origin request validation using Fetch Metadata headers.
/// </summary>
public interface ICrossOriginAntiforgery
{
/// <summary>
/// Validates the incoming HTTP request against cross-origin antiforgery requirements.
/// </summary>
/// <param name="context">The HTTP context representing the current request to validate.</param>
/// <returns>A <see cref="CrossOriginValidationResult"/> indicating whether the request is allowed, denied, or unknown.</returns>
CrossOriginValidationResult Validate(HttpContext context);
}
54 changes: 54 additions & 0 deletions src/Antiforgery/src/CrossOriginAntiforgeryMiddleware.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Middleware that performs cross-origin-only antiforgery validation.
/// Unknown results are treated as denied (strict mode).
/// </summary>
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<IAntiforgeryMetadata>() 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<IAntiforgeryValidationFeature>(new AntiforgeryValidationFeature(isValid: false, exception: null));
await _next(context);
}
}
99 changes: 99 additions & 0 deletions src/Antiforgery/src/Internal/CrossOriginRequestValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// 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.Extensions.Options;

namespace Microsoft.AspNetCore.Antiforgery.Internal;

/// <summary>
/// Validates cross-origin requests using Fetch Metadata headers (Sec-Fetch-Site)
/// and Origin header as a fallback.
/// </summary>
internal sealed class CrossOriginRequestValidator : ICrossOriginAntiforgery
{
private const string SecFetchSiteHeaderName = "Sec-Fetch-Site";
private const string SecFetchSiteSameOrigin = "same-origin";
private const string SecFetchSiteNone = "none";

private readonly CrossOriginAntiforgeryOptions _options;

public CrossOriginRequestValidator(IOptions<CrossOriginAntiforgeryOptions> options)
{
_options = options.Value;
}

public CrossOriginValidationResult Validate(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);

var request = context.Request;
Comment on lines +26 to +31

Copilot AI Mar 20, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ICrossOriginAntiforgery is a public API, but CrossOriginRequestValidator.Validate() does not account for safe methods (GET/HEAD/OPTIONS/TRACE) and can return Denied purely based on headers. Either incorporate the safe-method allowance into Validate() or clarify in the interface/docs that the caller is expected to pre-filter to only the methods/endpoints that require antiforgery validation.

Suggested change
public CrossOriginValidationResult Validate(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
var request = context.Request;
/// <summary>
/// Validates the specified HTTP context for potential cross-origin attacks.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> associated with the current request.</param>
/// <returns>
/// A <see cref="CrossOriginValidationResult"/> value indicating whether the request is allowed,
/// denied, or requires additional validation.
/// </returns>
/// <remarks>
/// This method always treats HTTP safe methods (<c>GET</c>, <c>HEAD</c>, <c>OPTIONS</c>, and <c>TRACE</c>)
/// as allowed and does not apply cross-origin antiforgery checks to them.
/// </remarks>
/// <example>
/// <code>
/// var result = crossOriginAntiforgery.Validate(httpContext);
/// if (result == CrossOriginValidationResult.Denied)
/// {
/// // Handle denied cross-origin request
/// }
/// </code>
/// </example>
public CrossOriginValidationResult Validate(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
var request = context.Request;
if (HttpMethods.IsGet(request.Method) ||
HttpMethods.IsHead(request.Method) ||
HttpMethods.IsOptions(request.Method) ||
HttpMethods.IsTrace(request.Method))
{
return CrossOriginValidationResult.Allowed;
}

Copilot uses AI. Check for mistakes.
var headers = request.Headers;

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))
{
if (string.Equals(secFetchSite, SecFetchSiteSameOrigin, StringComparison.OrdinalIgnoreCase) ||
string.Equals(secFetchSite, SecFetchSiteNone, StringComparison.OrdinalIgnoreCase))
{
return CrossOriginValidationResult.Allowed;
}

return CrossOriginValidationResult.Denied;
}

// Step 3: Fallback to Origin vs Host comparison (older browsers)
if (hasOrigin)
{
return OriginMatchesHost(origin, headers.Host.ToString())
? CrossOriginValidationResult.Allowed
: CrossOriginValidationResult.Denied;
}

// Step 4: Neither Sec-Fetch-Site nor Origin is present
return CrossOriginValidationResult.Unknown;
}

private bool IsTrustedOrigin(string origin)
{
foreach (var trustedOrigin in _options.TrustedOrigins)
{
if (string.Equals(origin, trustedOrigin, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}

return false;
}

private static bool OriginMatchesHost(string origin, string host)
{
if (string.IsNullOrEmpty(host))
{
return false;
}

if (!Uri.TryCreate(origin, UriKind.Absolute, out var originUri))
{
return false;
}

var originHost = originUri.IsDefaultPort
? originUri.Host
: $"{originUri.Host}:{originUri.Port}";

return string.Equals(originHost, host, StringComparison.OrdinalIgnoreCase);
}
}
Loading
Loading