我正在努力让我的 .net core 1.1 应用程序在负载均衡器后面工作并强制执行 https。我的 Startup.cs 中有以下设置
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IOptions<Auth0Settings> auth0Settings)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var startupLogger = loggerFactory.CreateLogger<Startup>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
startupLogger.LogInformation("In Development");
}
else
{
startupLogger.LogInformation("NOT in development");
app.UseExceptionHandler("/Home/Error");
}
app.UseMiddleware<HttpsRedirectMiddleware>();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});`
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme= CookieAuthenticationDefaults.AuthenticationScheme,
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieHttpOnly = true,
SlidingExpiration = true
});
HttpsRedirectMiddleware 用于验证 LB 是否设置了 X-Forwarded-Proto,它确实设置了,并且以 https 作为唯一值返回。当我访问网站 (https://myapp.somedomain.net) 时,它知道我没有通过身份验证并将我重定向到 (http://myapp.somedomain.net/Account/Logon?ReturnUrl=%2f)。它失去了 SSL 连接并切换回我的端口 80。 .net 核心文档说要像下面这样使用“UseForwardedHeaders”,这在我的情况下不起作用。发生此切换时,控制台记录器没有来自中间件的任何错误或警告。
为了短期修复,我将其放在“UseForwardedHeaders”下方
app.Use(async (context, next) =>
{
var xproto = context.Request.Headers["X-Forwarded-Proto"].ToString();
if (xproto!=null && xproto.StartsWith("https", StringComparison.OrdinalIgnoreCase)){
startupLogger.LogInformation("Switched to https");
context.Request.Scheme = "https";
}
await next();
});
上面的工作很完美,但是是一个 hack。我想以正确的方式去做。
最佳答案
.NET Core 有一个用于转发 header 的默认设置。对于 IIS 集成,它默认为 127.0.0.1。
追踪源代码后,我发现您可以清除KnownNetworks
和KnownProxies
列表以接受任何转发的请求。但是,最好仍然设置防火墙或将已知网络锁定到私有(private)子网。
var forwardingOptions = new ForwardedHeadersOptions()
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
forwardingOptions.KnownNetworks.Clear(); // Loopback by default, this should be temporary
forwardingOptions.KnownProxies.Clear(); // Update to include
app.UseForwardedHeaders(forwardingOptions);
.NET Core 2.x 的更新:记住在调试问题后设置代理/负载均衡器或专用网络的 IP。这可以防止绕过您的代理/负载平衡器并伪造 Forwarded-For
header 。
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardLimit = 2;
// Replace with IP of your proxy/load balancer
options.KnownProxies.Add(IPAddress.Parse("192.168.1.5"));
// 192.168.1.0/24 allows any from 192.168.1.1-254;
options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("192.168.1.0"), 24));
});
关于c# - .net Core X Forwarded Proto 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43749236/