.net Core X Forwarded Proto 不工作 [英] .net Core X Forwarded Proto not working

查看:21
本文介绍了.net Core X Forwarded Proto 不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力让我的 .net core 1.1 应用程序在负载平衡器后面工作并强制执行 https.我的 Startup.cs 中有以下设置

I am working to get my .net core 1.1 application working behind a load balancer and enforcing https. I have the following setup in my 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"如下所示,这在我的情况下不起作用.当这个切换发生时,控制台记录器没有来自中间件的任何错误或警告.

The HttpsRedirectMiddleware is for validating the LB has the X-Forwarded-Proto set, it does, and comes back as https as the only value. When I go to the site (https://myapp.somedomain.net), it knows I am not authenticated and redirects me to (http://myapp.somedomain.net/Account/Logon?ReturnUrl=%2f). It loses the SSL connection and switched back over to port 80 on me. The .net core documentation says to use "UseForwardedHeaders" like below, which does not work in my case. The console logger does not have any error or warnings from the middleware when this switch happens.

为了短期修复,我把它放在UseForwardedHeaders"下面

For a short term fix, I have put this below "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();

    });

以上工作完美,但是是一个黑客.我想以正确的方式去做.

The above works perfect, but is a hack. I would like to do it the correct way.

推荐答案

.NET Core 对转发的标头有一个默认设置.默认为 127.0.0.1,用于 IIS 集成.

.NET Core has a default set for the forwarded headers. It defaults to 127.0.0.1, for IIS integration.

追踪源代码后,我发现您可以清除KnownNetworksKnownProxies 列表以接受任何转发的请求.但是,最好设置防火墙或将已知网络锁定到私有子网.

After tracking down the source code, I found that you can clear the KnownNetworks and KnownProxies lists to accept any forwarded requests. However, it is still best to have a firewall setup or lock the known networks down to a private subnet.

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 标头.

Update for .NET Core 2.x: Remember setting the IP of your proxy/load balancer or the private network after debugging the issue. This prevents bypassing your proxy/load balancer and faking the Forwarded-For headers.

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));
});

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2#forwarded-headers-middleware-选项

这篇关于.net Core X Forwarded Proto 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆