【问题标题】:Configure Strict Cors .Net Core 3.1配置严格的 Cors .Net Core 3.1
【发布时间】:2020-11-24 22:14:55
【问题描述】:

我有一个公共分析网络 API (.Net Core 3.1),它从我的各种网络应用程序和网站(页面视图等)中捕获基本分析。我非常想以更严格的方式配置 cors,因为我很清楚流量应该来自哪里。值得注意的是,我正在将此应用程序从 .Net Core 2.2 更新为 .Net Core 3.1

我的Startup.cs 文件中有以下方法

public void ConfigureServices(IServiceCollection services)
{
  ...
  ConfigureCors(services);
}

private void ConfigureCors(IServiceCollection services)
{
  // https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas
  services.AddCors(options =>
  {
        options.AddPolicy("CorsPolicy",
             builder => builder.WithOrigins(AppConfiguration.CorsOrigins)
             .AllowAnyMethod()
             .AllowAnyHeader());
  });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();
      app.UseCors("CorsPolicy");
      app.UseAuthentication();
      app.UseAuthorization();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers().RequireAuthorization();
      });
  }

AppConfiguration 是我用来处理配置的一个类,它使用以下方法获取 json 值:
public string[] CorsOrigins => _config["CorsOrigins"].Split(',');

appsettings.Development.json,我有"CorsOrigins": "*"

我非常想在 appsettings.Production.jsonappsettings.Staging.json 文件中指定严格的来源。
例如。 "CorsOrigins": "https://subdomain.example.com,https://www.example.com,https://example.com",但在部署时,每当网站/应用程序访问各个端点时,我都会获得502 的状态。

"CorsOrigins": "*" 在本地工作,所以据我所知,Startup.cs 文件不会有任何问题。

更新: "CorsOrigins": "*" 实际上也不适用于暂存或生产环境。现在我更加困惑了。需要明确的是,这是一个cors 问题。在升级到 .Net Core 3.1 之前,以下工作正常:

private void ConfigureCors(IServiceCollection services)
      services.AddCors(options =>
      {
        options.AddPolicy("CorsPolicy",
             builder => builder.AllowAnyOrigin()
             .AllowAnyMethod()
             .AllowAnyHeader()
             .AllowCredentials());
      });
    }

【问题讨论】:

  • 您是否正在为“消耗”您的 appsettings.ENVIRONMENT.json(请参阅 docs.microsoft.com/en-us/aspnet/core/fundamentals/…)而苦苦挣扎,或者......您的 appsettings.ENVIRONMENT.json 文件中的值(针对您的特定 CORS)正在搞砸你呢?
  • @granadaCoder 应用程序设置的消耗是黄金,它与“*”或上面提供的示例形式的源数组不匹配。 IE。如果我调试,AppConfiguration.CorsOrigins 的预期值取决于环境。
  • 根据文档,如果存在 Access-Control-Allow-Credentials 标头,则将源设置为“*”(所有源)的 CORS 规范无效。 docs.microsoft.com/en-us/aspnet/core/security/…
  • @pbachman 正确。在迁移到 .Net Core 3.1 时,AllowCredentials 已被删除,因为它在使用“*”时无效(有关之前的代码,请参阅“更新”)。在我的情况下,由于选项是“*”、“example.com”等,AllowCredentials 也不能使用并且已被删除(请参阅“更新”部分上方的当前情况。没有 Access-Control-Allow-Credentials 标题出现在我的请求中。

标签: c# asp.net-core .net-core


【解决方案1】:

抱歉,这是一个困难的问题,因此可能有很多原因它不起作用,但我遇到了类似的问题,并通过更改 Configure() 函数中的 cors 调用解决了它。 Configure() 函数在运行时被调用并充当 http 请求管道,因此在某些情况下执行顺序很重要 (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-3.1#the-configure-method)

您可以尝试以下方法:

改变电流:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();
      app.UseAuthentication();
      app.UseAuthorization();
      app.UseCors("CorsPolicy"); //Move this line 

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers().RequireAuthorization();
      });
  }

收件人:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseCors("CorsPolicy"); // Here

      app.UseAuthentication();
      app.UseAuthorization();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers().RequireAuthorization();
      });
  }

因此,http 管道中的第一个操作是验证 cors。 我认为这是一个公平的赌注,因为从您的问题来看,听起来您没有收到应用程序初始化错误,而是出现运行时客户端请求时间错误。 我不确定这是否会解决问题,但也许会有所帮助!

【讨论】:

  • 文档声明“对 UseCors 的调用必须放在 UseRouting 之后,但在 UseAuthorization 之前。”
  • 谢谢@NoahStahl :) 我从未见过!感谢您的帮助-我更新了我的答案以遵守:)
【解决方案2】:

注意将 UseCors 放置在正确的位置。来自the docs

对 UseCors 的调用必须放在 UseRouting 之后,但 之前 使用授权。

如 cmets 中所述,AllowCredentials 不允许使用“*”作为来源。

这是一个来自我的 ASPNET Core 3.1 项目的 CORS 配置的工作示例。它在 Configure 方法而不是 ConfigureServices 中进行配置,但内容相同:

// Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    // etc
}

public void Configure(IApplicationBuilder app)
{
    // other configs

    app.UseRouting();

    // CORS configuration. Expects allowed origins as comma-separated list in config under 'Cors:AllowedOrigins'.
    string configuredOrigins = Configuration["Cors:AllowedOrigins"] ?? throw new ArgumentNullException("Cors:AllowedOrigins");
    string[] origins = configuredOrigins.Split(',', ';').Select(i => i.Trim()).ToArray();
    app.UseCors(policy => policy
        .WithOrigins(origins)
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials() // Required by SignalR
        .WithExposedHeaders(CONTINUATION_HEADER_KEY) // Allow use of custom header
        .SetPreflightMaxAge(TimeSpan.FromSeconds(86400))); // Allow caching for 24 hours (depends on browser)

    app.UseAuthentication();
    app.UseAuthorization();

    // other configs
}

【讨论】:

  • 感谢您的样品。恐怕我仍然遵循between UseRouting` 和UseAuthorization 规则得到502。我在帖子中添加了一张图片,显示了失败请求的所有信息。为简单起见,我已恢复使用AllowAnyOrigin 来排除一些可能性,因为我的2.2 版本也在AllowAnyOrigin 上。
猜你喜欢
  • 2021-01-03
  • 2020-07-30
  • 2020-08-22
  • 2018-10-13
  • 2020-05-22
  • 2021-10-16
  • 2021-07-27
  • 2020-04-06
  • 1970-01-01
相关资源
最近更新 更多