Skip to content

Commit af65ca6

Browse files
Adds support for filtering requests by headers. Closes #740 (#755)
1 parent a63660a commit af65ca6

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

dev-proxy/ProxyConfiguration.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,6 @@ public class ProxyConfiguration : IProxyConfiguration
3636
public string ConfigFile { get; set; } = "devproxyrc.json";
3737
[JsonConverter(typeof(JsonStringEnumConverter))]
3838
public ReleaseType NewVersionNotification { get; set; } = ReleaseType.Stable;
39+
public MockRequestHeader[]? FilterByHeaders { get; set; }
3940
}
4041

dev-proxy/ProxyEngine.cs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,7 +506,8 @@ private bool IsProxiedProcess(TunnelConnectSessionEventArgs e)
506506

507507
async Task OnRequest(object sender, SessionEventArgs e)
508508
{
509-
if (IsProxiedHost(e.HttpClient.Request.RequestUri.Host))
509+
if (IsProxiedHost(e.HttpClient.Request.RequestUri.Host) &&
510+
IsIncludedByHeaders(e.HttpClient.Request.Headers))
510511
{
511512
_pluginData.Add(e.GetHashCode(), []);
512513
var responseState = new ResponseState();
@@ -553,6 +554,43 @@ private async Task HandleRequest(SessionEventArgs e, ProxyRequestArgs proxyReque
553554

554555
private bool IsProxiedHost(string hostName) => _hostsToWatch.Any(h => h.Url.IsMatch(hostName));
555556

557+
private bool IsIncludedByHeaders(HeaderCollection requestHeaders)
558+
{
559+
if (_config.FilterByHeaders is null)
560+
{
561+
return true;
562+
}
563+
564+
foreach (var header in _config.FilterByHeaders)
565+
{
566+
_logger.LogDebug("Checking header {header} with value {value}...",
567+
header.Name,
568+
string.IsNullOrEmpty(header.Value) ? "(any)" : header.Value
569+
);
570+
571+
if (requestHeaders.HeaderExists(header.Name))
572+
{
573+
if (string.IsNullOrEmpty(header.Value))
574+
{
575+
_logger.LogDebug("Request has header {header}", header.Name);
576+
return true;
577+
}
578+
579+
if (requestHeaders.GetHeaders(header.Name)!.Any(h => h.Value.Contains(header.Value)))
580+
{
581+
_logger.LogDebug("Request header {header} contains value {value}", header.Name, header.Value);
582+
return true;
583+
}
584+
}
585+
else
586+
{
587+
_logger.LogDebug("Request doesn't have header {header}", header.Name);
588+
}
589+
}
590+
591+
_logger.LogDebug("Request doesn't match any header filter. Ignoring");
592+
return false;
593+
}
556594

557595
// Modify response
558596
async Task OnBeforeResponse(object sender, SessionEventArgs e)

0 commit comments

Comments
 (0)