Skip to content

Commit

Permalink
Added a condition so the anti-forgery check can be skipped in cases l…
Browse files Browse the repository at this point in the history
…ike an API request
  • Loading branch information
FrostyApeOne authored and FrostyApeOne committed Feb 18, 2025
1 parent 3ba0dbd commit 3da1db0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Microsoft.AspNetCore.Http;

namespace DfE.CoreLibs.Security.Cypress
{
public class CypressAwareAntiForgeryOptions
{
/// <summary>
/// A function that, given the current <see cref="HttpContext"/>,
/// returns <c>true</c> if antiforgery should be skipped, or <c>false</c> otherwise.
/// </summary>
public Func<HttpContext, bool> ShouldSkipAntiforgery { get; set; }
= _ => false; // Default: never skip
}
}
22 changes: 15 additions & 7 deletions src/DfE.CoreLibs.Security/Cypress/CypressAwareAntiforgeryFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,30 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace DfE.CoreLibs.Security.Cypress
{
/// <summary>
/// An authorization filter that enforces AntiForgery validation for all requests,
/// except for those recognized as valid Cypress requests.
/// except for those recognized as valid Cypress requests or for which the
/// configured predicate says to skip.
/// </summary>
public class CypressAwareAntiForgeryFilter(
IAntiforgery antiForgery,
IAntiforgery antiforgery,
ILogger<CypressAwareAntiForgeryFilter> logger,
ICypressRequestChecker cypressChecker)
ICypressRequestChecker cypressChecker,
IOptions<CypressAwareAntiForgeryOptions> optionsAccessor)
: IAsyncAuthorizationFilter
{
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (optionsAccessor.Value.ShouldSkipAntiforgery(context.HttpContext))
{
logger.LogInformation("Skipping antiforgery due to ShouldSkipAntiforgery predicate.");
return;
}

var method = context.HttpContext.Request.Method;
if (HttpMethods.IsGet(method) || HttpMethods.IsHead(method) ||
HttpMethods.IsOptions(method) || HttpMethods.IsTrace(method))
Expand All @@ -28,13 +37,12 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
var isCypress = cypressChecker.IsCypressRequest(context.HttpContext);
if (isCypress)
{
logger.LogInformation("Skipping AntiForgery for Cypress request");
logger.LogInformation("Skipping antiforgery for Cypress request.");
return;
}

logger.LogInformation("Enforcing AntiForgery for non-Cypress request");
await antiForgery.ValidateRequestAsync(context.HttpContext);
logger.LogInformation("Enforcing antiforgery for non-Cypress request.");
await antiforgery.ValidateRequestAsync(context.HttpContext);
}
}

}

0 comments on commit 3da1db0

Please sign in to comment.