Skip to content

Commit

Permalink
Allow reverse proxies to pass forwarded headers allowing for api acce…
Browse files Browse the repository at this point in the history
…ss without disabling https redirection middleware (#1937)

* Working concept.

* only add forwarding headers if known proxies is non-empty

---------

Co-authored-by: Robbie Lodico <[email protected]>
  • Loading branch information
jcsnider and lodicolo authored Oct 10, 2023
1 parent 0459dcf commit e83f25f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Intersect.Server/Web/Net7/ApiService.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Net;
using System.Reflection;
using System.Threading.RateLimiting;
using Intersect.Core;
Expand All @@ -17,6 +18,7 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.OData;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -208,8 +210,30 @@ internal partial class ApiService : ApplicationService<ServerContext, IApiServic
builder.Services.AddProblemDetails();
}

if (configuration.KnownProxies.Count > 0)
{
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;

foreach (var proxy in configuration.KnownProxies)
{
if (IPAddress.TryParse(proxy, out IPAddress address))
{
Log.Info($"Added \"{proxy}\" as good known proxy for forwarded headers middleware.");
options.KnownProxies.Add(address);
}
else
{
Log.Error($"Failed to parse \"{proxy}\" as good known proxy for forwarded headers middleware.");
}
}
});
}

var app = builder.Build();

app.UseForwardedHeaders();
app.UseNetworkFilterMiddleware(configuration.AllowedNetworkTypes);

if (app.Environment.IsDevelopment())
Expand Down
4 changes: 4 additions & 0 deletions Intersect.Server/Web/Net7/Configuration/ApiConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Immutable;
using System.ComponentModel;
using System.Net;
using Intersect.Server.Web.RestApi.Configuration;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Cors.Infrastructure;
Expand Down Expand Up @@ -51,6 +52,9 @@ public ImmutableDictionary<string, CorsPolicy>? Cors
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore)]
public TokenGenerationOptions? TokenGenerationOptions { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<string> KnownProxies { get; set; } = new List<string>();

#endregion
}
}

0 comments on commit e83f25f

Please sign in to comment.