.Net核心X-Forwarded-Proto标头未正确传递给Nginx [英] .Net core X-Forwarded-Proto header doesn't pass to Nginx properly

查看:185
本文介绍了.Net核心X-Forwarded-Proto标头未正确传递给Nginx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,编辑历史记录,但是这个问题对我来说真的很不清楚,很难找到确切的问题.

Sorry for the edit history but this issue was really unclear to me and it was difficult to locate the exact problem.

我有一个 .Net-Core Web应用程序,该应用程序在 Nginx 之后运行,并且 X-Forwarded-Proto 始终通过http而不是https.

I have a .Net-Core web application that runs behind a Nginx and the X-Forwarded-Proto always passes http instead of https.

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });

            services.AddMvc();

        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //first middlewear
            app.UseForwardedHeaders();
             //and the rest
         }

Nginx conf

server {
    listen        80;
    server_name   example.com;
    location / {
        proxy_pass         http://localhost:5001/;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

Nginx.conf

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    #cloudflare real ip
    #https://support.cloudflare.com/hc/en-us/articles/200170786-Restoring-original-visitor-IPs-Logging-visitor-IP-addresses-with-mod-cloudflare-#12345681
    set_real_ip_from 173.245.48.0/20;
    real_ip_header    X-Forwarded-For;
    real_ip_recursive on;

    log_format  main  '"$scheme" $remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

access.log记录

"http" 185.108.83.156 - - [03/Oct/2019:19:59:33 +0300] "GET /auth/signin/Facebook?returnUrl=%2F HTTP/1.1" 302 0 "https://example.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36" "156"

您可以看到我登录的 $ scheme 始终是 HTTP .

as you can see the $scheme that I log is always HTTP.

解决此问题的一种方法是将Scheme强制为 HTTPS ,如下所示:

A solution that solves the issue is to enforce Scheme to be HTTPS like so:

app.Use((context, next) =>
        {
            context.Request.Scheme = "https";
            return next();
        });

来自但是使用这种解决方案,我不会传递标头,并且会丢失一些信息.

But with this solution I don't pass the headers and loses some information.

那么有人对此案有什么解决办法吗?

So does anyone have any solution for this case?

推荐答案

您的Startup.cs文件很好,但是您没有为Kesterl配置ssl.

Your Startup.cs file is fine but you didn't configure ssl for Kesterl.

您需要为.net核心应用程序配置X.509 ssl证书

You need to configure a X.509 ssl certificate for your .net core application

来自

仅反向代理服务器需要X.509证书,并且该证书 服务器可以与内部网络上的应用服务器通信 使用纯HTTP

Only the reverse proxy server requires an X.509 certificate, and that server can communicate with the app's servers on the internal network using plain HTTP

因此,在您的情况下,您需要执行7个主要步骤:
1)从CloudFlare ORIGIN CA获取SSL证书
2)在服务器中安装ssl证书
3)创建一个PFX文件,以便您的Kesterl Server可以读取它.
4)配置Kesterl https端点.
5)修改Nginx服务器以侦听端口443,然后重定向到Kestrel侦听端口
6)根据您的配置相应地修改服务文件
7)将Cloudflare更改为运行严格模式

So in your case you have 7 main steps to do:
1) Get a SSL certificate from CloudFlare ORIGIN CA
2) Install the ssl certificate in your server
3) Create a PFX file so your Kesterl Server can read it.
4) Configure Kesterl https end points.
5) Modify your Nginx server to listen to port 443 and then redirect to Kestrel listening ports
6) Modify service files accordingly your configuration
7) Change Cloudflare to run Strict mode

步骤1-从cloudflare获取ssl证书:
转到Cloudflare的信息中心,然后选择SSL/TLS->源服务器->创建证书. 按照说明进行操作,然后在过程结束时将有2个文件: example.com.key example.com.pem

Step 1 - Get ssl certificate from cloudflare:
Go to your dashboard at Cloudflare and choose SSL/TLS --> Origin Server -->Create Certificate. Follow the instructions and you will have 2 files at the end of the process: example.com.key example.com.pem

第2步-将文件放在服务器中的etc/ssl文件夹

Step 2 - Place the files in your server at etc/ssl folder

第3步-创建PFX文件,以便Kesterl可以使用证书:
在您的服务器上运行它:

Step 3 - Create PFX file so Kesterl can use the certificate:
run this at your server:

openssl pkcs12 -export -out example.pfx -inkey example.com.key -in example.com.pem

这将生成 example.pfx ,并将其放置在同一文件夹中.

This will generate the example.pfx, place it in the same folder.

第4步-配置Kesterl https端点.
从步骤3开始,您应该已经在该步骤中需要使用密码.
在您的appsetting.json处放置以下行:

Step 4 - Configure Kesterl https end points.
From step 3 you should have got a password that you need to use at this step.
At your appsetting.json place this lines:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Kestrel": {
    "Endpoints": {
      "HTTPS": {
        "Url": "https://localhost:5001",
        "Certificate": {
          "Path": "/etc/ssl/example.pfx",
          "Password": "**********"
        }
      }
    }
  }

第5步-配置Nginx监听端口443,如下所示:

server {
    #listen        80;
    listen                 *:443 ssl;
    ssl_certificate        /etc/ssl/example.pem;
    ssl_certificate_key    /etc/ssl/example.key;
    server_name            example.com
    location / {
        proxy_pass         https://localhost:5001/;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

第6步-像这样配置服务文件:

  [Unit]
    Description=example

    [Service]
    WorkingDirectory=/var/www/example
    ExecStart=/usr/bin/dotnet /var/www/example/exampleSite.dll
    Restart=always
    # Restart service after 10 seconds if the dotnet service crashes:
    RestartSec=10
    KillSignal=SIGINT
    SyslogIdentifier=example
    User=www-data
    Environment=ASPNETCORE_ENVIRONMENT=Staging
    Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
    Environment=ASPNETCORE_HTTPS_PORT=5001
    Environment=ASPNETCORE_URLS=https://localhost:5001

    [Install]
    WantedBy=multi-user.target

步骤7-将SSL/TLS上的Cloudflare更改为使用严格模式

重新启动您的应用程序+ Nginx,您的服务器现在应该像这样工作:

Restart your application + Nginx and your server should now work like this:

请求-> Cloudflare(HTTPS)-> Nginx(HTTPS)-> Example.com

Request --> Cloudflare(HTTPS) --> Nginx(HTTPS)-->Example.com

这篇关于.Net核心X-Forwarded-Proto标头未正确传递给Nginx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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