Nginx代理AspNetCore跨域问题

在前后端分离开发中,经常出现跨域的问题,本文是记录使用Nginx来反向代理AspNetCore应用时的跨域问题

跨域

对于同一域名(主机名),同一端口,同一协议,我们认为这是同一个域,只要有一个条件不满足,就会产生跨域问题,防止跨域本身是为了主机安全,所以推荐尽量从服务端进行控制,客户端控制不在本文范围内

解决跨域

开发

开发 asp.net core 应用时,我们可以使用跨域中间件来允许所有域访问,方便进行接口调试和测试

//Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
      if (env.IsDevelopment())
      {
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
      }
 }

单体部署

但是正式生产环境中,不允许这样使用,也就是说即使配置了也还是会失效,推荐使用白名单模式,可以扩展配置文件 appsetting.json 文件,加上跨域配置

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Server": "sql connection string"
  },
  "Cors": {
    "Open": true,
    "Policy": "http://www.ex.com"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

其中的 Cors 配置为跨域项,然后根据该项配置跨域,下面只是简单展示,具体还应加上验证

//Startup.cs 中 ConfigureServices
services.AddCors(options =>
{
    options.AddPolicy(name: "prod",
                      builder =>
                      {
                          if (Convert.ToBoolean(Configuration.GetSection("Cors").GetSection("Open").Value))
                          {
                              var cors = Configuration.GetSection("Cors").GetSection("Policy").Value.Split(',');
                              builder.WithOrigins(cors).WithMethods("GET", "POST", "OPTIONS");
                          }
                      });
});

//Startup.cs 中 Configure
app.UseCors("prod");

Nginx部署

使用 Nginx 进行反向代理,需要在 Nginx 上配置跨域规则,同时需要清除应用中的跨域规则,不然会出现两个跨域规则导致出错,配置 nginx.conf 如下

location / {
     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
     }
}
发布时间:2021-10-13