From 0dcc78452b6e9606da23e2663981b0538b8520e2 Mon Sep 17 00:00:00 2001 From: Thomas Jespersen Date: Tue, 16 Jan 2024 12:31:37 +0100 Subject: [PATCH] Temporarily implement CSRF check for all POST, PUT, PATCH, and DELETE endpoints except /api/track --- .../ApiCore/ApiCoreConfiguration.cs | 29 +++++++++++++++++-- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/application/shared-kernel/ApiCore/ApiCoreConfiguration.cs b/application/shared-kernel/ApiCore/ApiCoreConfiguration.cs index 17a828beb..fe1ccaae2 100644 --- a/application/shared-kernel/ApiCore/ApiCoreConfiguration.cs +++ b/application/shared-kernel/ApiCore/ApiCoreConfiguration.cs @@ -1,5 +1,6 @@ using System.Text.Json; using Microsoft.ApplicationInsights.AspNetCore.Extensions; +using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Json; @@ -134,6 +135,31 @@ public static WebApplication AddApiCoreConfiguration(this WebApplica app.UseMiddleware(); + + // Enable support for CSRF tokens + app.UseAntiforgery(); + app.Use(async (context, next) => + { + if (context.Request.Path.StartsWithSegments("/api/track", StringComparison.OrdinalIgnoreCase)) + { + // Hack: to disable CSRF token validation for the track endpoint + await next.Invoke(); + return; + } + + // Validate CSRF tokens for all POST, PUT, PATCH and DELETE requests + if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase) || + string.Equals(context.Request.Method, "PUT", StringComparison.OrdinalIgnoreCase) || + string.Equals(context.Request.Method, "PATCH", StringComparison.OrdinalIgnoreCase) || + string.Equals(context.Request.Method, "DELETE", StringComparison.OrdinalIgnoreCase)) + { + var antiforgery = context.RequestServices.GetService()!; + await antiforgery.ValidateRequestAsync(context); + } + + await next.Invoke(); + }); + // Configure track endpoint for Application Insights telemetry for PageViews and BrowserTimings app.MapTrackEndpoints(); @@ -142,9 +168,6 @@ public static WebApplication AddApiCoreConfiguration(this WebApplica app.Services.ApplyMigrations(); - // Enable support for CSRF tokens - app.UseAntiforgery(); - return app; } } \ No newline at end of file