Skip to content

Commit

Permalink
Temporarily implement CSRF check for all POST, PUT, PATCH, and DELETE…
Browse files Browse the repository at this point in the history
… endpoints except /api/track
  • Loading branch information
tjementum committed Jan 16, 2024
1 parent 96a519a commit 0dcc784
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions application/shared-kernel/ApiCore/ApiCoreConfiguration.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -134,6 +135,31 @@ public static WebApplication AddApiCoreConfiguration<TDbContext>(this WebApplica

app.UseMiddleware<ModelBindingExceptionHandlerMiddleware>();


// 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<IAntiforgery>()!;
await antiforgery.ValidateRequestAsync(context);
}

await next.Invoke();
});

// Configure track endpoint for Application Insights telemetry for PageViews and BrowserTimings
app.MapTrackEndpoints();

Expand All @@ -142,9 +168,6 @@ public static WebApplication AddApiCoreConfiguration<TDbContext>(this WebApplica

app.Services.ApplyMigrations<TDbContext>();

// Enable support for CSRF tokens
app.UseAntiforgery();

return app;
}
}

0 comments on commit 0dcc784

Please sign in to comment.