.net Core X转发的协议不起作用 [英] .net Core X Forwarded Proto not working

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

问题描述

我正在努力让我的.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();

    });

上面的方法很完美,但是很hack。我想以正确的方式做。

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

推荐答案

.net Core为转发的标头设置了默认设置。对于IIS集成,默认值为127.0.0.1。跟踪源代码后,您可以清除已知网络和已知代理以接受任何转发的请求。最好还是设置防火墙或将已知网络锁定到专用子网。

.net Core has a default set for the forwarded headers. It defaults to 127.0.0.1, for IIS integration. After tracking down the source code, you can clear the Known Networks and Known Proxies to accept any forwarded requests. 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);

更新。调试问题后,设置代理/负载平衡器或专用网络的IP。这样可以避免绕过代理/负载平衡器并伪造转发标头。

Update for dotnet net core 2.x. Set the IP of the 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;
    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;

https://docs.microsoft.com/zh-cn/aspnet/ core / host-and-deploy / proxy-load-balancer?view = aspnetcore-2.2#forwarded-headers-middleware-options

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

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