我正在努力让我的.net核心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();
});
以上作品非常完美,但却是一种黑客攻击。我想以正确的方式做到这一点。
答案 0 :(得分:36)
.net Core为转发的标头设置了默认设置。对于IIS集成,它默认为127.0.0.1。在跟踪源代码后,您可以清除已知网络和已知代理以接受任何转发的请求。最好还是设置防火墙或将已知网络锁定到私有子网。
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);
dotnet net core 2.x的更新。调试问题后,设置代理/负载均衡器或专用网络的IP。这可以防止绕过您的代理/负载均衡器并伪造转发的标头。
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardLimit = 2;
options.KnownProxies.Add(IPAddress.Parse("192.168.1.5")); //Replace with IP of your proxy/load balancer
options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("192.168.1.0"),24));;
}) //192.168.1.0/24 allows any from 192.168.1.1-254;
答案 1 :(得分:0)
如果您使用的是负载平衡器,通常是让负载平衡终止SSL连接,然后通过HTTP将请求发送到您的应用程序。
这对我有用。我在AWS Load Balancer上使用SSL终止。
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto
});
这是用X-Forwarded-Proto标头更新Request.Scheme,以便所有重定向链接生成都使用正确的方案。
X-Forwarded-Proto:来自原始客户端和代理的方案。