From fafa5ae02a91837898034a7a1e28d2c7c66bff6a Mon Sep 17 00:00:00 2001 From: bicijinlian Date: Sat, 1 May 2021 13:47:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CorsServer.WebApi31/Config/CorsOption.cs | 18 +- CorsServer/CorsServer.WebApi31/Startup.cs | 198 +++++++++++++----- .../CorsServer.WebApi31/StartupConfig.cs | 127 +++++++++++ .../StartupDefaultPolicy.cs | 80 +++++++ .../CorsServer.WebApi31/appsettings.json | 4 +- 5 files changed, 364 insertions(+), 63 deletions(-) create mode 100644 CorsServer/CorsServer.WebApi31/StartupConfig.cs create mode 100644 CorsServer/CorsServer.WebApi31/StartupDefaultPolicy.cs diff --git a/CorsServer/CorsServer.WebApi31/Config/CorsOption.cs b/CorsServer/CorsServer.WebApi31/Config/CorsOption.cs index f818116..ba4cacb 100644 --- a/CorsServer/CorsServer.WebApi31/Config/CorsOption.cs +++ b/CorsServer/CorsServer.WebApi31/Config/CorsOption.cs @@ -8,23 +8,33 @@ namespace CorsServer.WebApi31 public class CorsOption { /// - /// 允许跨域的域名列表 + /// 允许跨域的请求来源 /// public List Origins { get; set; } /// - /// 允许跨域的方法 + /// 允许跨域的HTTP方法 /// public List Methods { get; set; } /// - /// 允许跨域的请求头 + /// 允许跨域的HTTP请求头 /// public List Headers { get; set; } /// - /// 允许跨域的ExposedHeader + /// 公开的非简单响应标头 /// public List ExposedHeaders { get; set; } + + /// + /// 允许跨域请求中的凭据 + /// + public bool AllowCredentials { get; set; } + + /// + /// 预检过期时间 + /// + public TimeSpan PreflightMaxAge { get; set; } } } diff --git a/CorsServer/CorsServer.WebApi31/Startup.cs b/CorsServer/CorsServer.WebApi31/Startup.cs index 379a9d8..acadfba 100644 --- a/CorsServer/CorsServer.WebApi31/Startup.cs +++ b/CorsServer/CorsServer.WebApi31/Startup.cs @@ -16,7 +16,7 @@ namespace CorsServer.WebApi31 { public class Startup { - public Startup(IConfiguration configuration,IHostEnvironment hostingEnvironment,IWebHostEnvironment webHostEnvironment) + public Startup(IConfiguration configuration, IHostEnvironment hostingEnvironment, IWebHostEnvironment webHostEnvironment) { Configuration = configuration; } @@ -25,9 +25,9 @@ namespace CorsServer.WebApi31 public void ConfigureServices(IServiceCollection services) { - #region Config + //Config services.Configure(Configuration.GetSection("CORS")); - #endregion + #region CORS AddCors_Test(services); //AddCors_2(services); @@ -60,51 +60,6 @@ namespace CorsServer.WebApi31 }); } - /// - /// ȫ˵ - /// - private IServiceCollection AddCors_Info(IServiceCollection services) - { - services.AddCors(setup => - { - setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => - { - build - - //Դ - .AllowAnyOrigin() //κԴ - //.WithOrigins() //ָԴ - .SetIsOriginAllowed(_ => true) //ʹFunc ίзȷǷԴ - .SetIsOriginAllowedToAllowWildcardSubdomains() //Դʹͨ(*) - - //󷽷(POST GET PUT DELETE OPTIONS) - .AllowAnyMethod() //з - //.WithMethods() //ָ - - //ͷ - .AllowAnyHeader() //ͷ - //.WithHeaders() //ָͷ - - //ƾ - .AllowCredentials() //ƾݣ֤а(cookies)HTTP֤Э(HTTP authentication schemes) - //.DisallowCredentials() //ܾƾ - - //.WithExposedHeaders() //ñ¶ԶӦͷĬ£ֻᱩ¶ĬϵӦͷӦãԶӰͷᱩ¶Ӧó - ; - - /*ر˵ - ڰȫǣ.net core 2.1ʼ, AllowAnyOrigin() AllowCredentials() ͬʱʹ - - 1ʹAllowCredentials()ʱ.SetIsOriginAllowed(_ => true) AllowAnyOrigin() - 2ʹAllowCredentials()ʱ WithOrigins()ָԴ(ʹSetIsOriginAllowedToAllowWildcardSubdomains()ͨ) AllowAnyOrigin() - 3Զм - */ - }); - }); - - return services; - } - /// /// CORS ģ /// @@ -118,8 +73,10 @@ namespace CorsServer.WebApi31 build //Դ + //1Դ .AllowAnyOrigin() - //.WithOrigins(corsOption.Origins.ToArray()) + + //2lamdaԶ //.SetIsOriginAllowed(requestOrigin => //{ // //Դ(Э++˿ںţ http://wwwww.xxxx.com:80) @@ -129,6 +86,10 @@ namespace CorsServer.WebApi31 // return true; //}) + + //3WithOriginsԶ + //.WithOrigins(corsOption.Origins.ToArray()) + //WithOriginsʹͨ(*) //.SetIsOriginAllowedToAllowWildcardSubdomains() //󷽷(POST GET PUT DELETE OPTIONS) @@ -144,6 +105,7 @@ namespace CorsServer.WebApi31 //.DisallowCredentials() //.WithExposedHeaders() + //.SetPreflightMaxAge(TimeSpan.FromMinutes(10)) ; }); }); @@ -151,6 +113,57 @@ namespace CorsServer.WebApi31 return services; } + /// + /// ȫ˵ + /// + private IServiceCollection AddCors_Info(IServiceCollection services) + { + services.AddCors(setup => + { + setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => + { + build + + //Դ + .AllowAnyOrigin() //κԴ + //.SetIsOriginAllowed(_=> true) //ʹFunc ίзԶǷԴ + //.WithOrigins() //ָԴ + //.SetIsOriginAllowedToAllowWildcardSubdomains() //WithOrigins()Դʹͨ(*) + + //HTTP(POST GET PUT DELETE OPTIONS) + .AllowAnyMethod() //з + //.WithMethods() //ָ + + //ͷ + .AllowAnyHeader() //ͷ + //.WithHeaders() //ָͷ + + //еƾ + .AllowCredentials() //ƾݣ֤а(cookies)HTTP֤Э(HTTP authentication schemes) + //.DisallowCredentials() //ܾƾ + + //ùķǼӦͷ /ñ¶ԶӦͷĬ£ֻᱩ¶ĬϵӦͷӦãԶӰͷᱩ¶Ӧó + .WithExposedHeaders("x-custom-a", "x-custom-b") + + //Ԥʱ + .SetPreflightMaxAge(TimeSpan.FromMinutes(10)) //˱ͷָɻԤӦʱ䳤 + ; + + /*ر˵ + ڰȫǣ.net core 2.1ʼ, AllowAnyOrigin() AllowCredentials() ͬʱʹ + + 1ʹAllowCredentials()ʱ.SetIsOriginAllowed(_ => true) AllowAnyOrigin() + 2ʹAllowCredentials()ʱ WithOrigins()ָԴ(ʹSetIsOriginAllowedToAllowWildcardSubdomains()ͨ) AllowAnyOrigin() + 3Զм + */ + }); + }); + + return services; + } + + #region ע᲻ͬCors + /// /// /// @@ -165,7 +178,7 @@ namespace CorsServer.WebApi31 //Դ //.AllowAnyOrigin() //.WithOrigins() - .SetIsOriginAllowed(requestOrigin => + .SetIsOriginAllowed(requestOrigin => { var cc = requestOrigin; return true; @@ -202,16 +215,16 @@ namespace CorsServer.WebApi31 //Դ .AllowAnyOrigin() - //.WithOrigins() - //.SetIsOriginAllowed(_ => true) - //.SetIsOriginAllowedToAllowWildcardSubdomains() + //.WithOrigins() + //.SetIsOriginAllowed(_ => true) + //.SetIsOriginAllowedToAllowWildcardSubdomains() - //󷽷(POST GET PUT DELETE OPTIONS) - //.AllowAnyMethod() - //.WithMethods() + //󷽷(POST GET PUT DELETE OPTIONS) + //.AllowAnyMethod() + //.WithMethods() - //ͷ - //.AllowAnyHeader() + //ͷ + //.AllowAnyHeader() //.WithHeaders() //ƾ @@ -294,5 +307,74 @@ namespace CorsServer.WebApi31 return services; } + + private IServiceCollection AddCors_Config(IServiceCollection services) + { + services.AddCors(setup => + { + var corsOption = services.BuildServiceProvider().GetRequiredService>().Value; + setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, builder => + { + if (corsOption.Origins == null) + { + builder.SetIsOriginAllowed(_ => true); + } + else if (corsOption.Origins.Count == 0) + { + builder.SetIsOriginAllowed(_ => true); + } + else if (corsOption.Origins.Contains("*")) + { + builder.SetIsOriginAllowed(_ => true); + } + else + { + builder.WithOrigins(corsOption.Origins.ToArray()); + builder.SetIsOriginAllowedToAllowWildcardSubdomains(); + } + + if (corsOption.Methods == null || corsOption.Methods.Count == 0) + { + builder.AllowAnyMethod(); + } + else + { + builder.WithMethods(corsOption.Methods.ToArray()); + } + + if (corsOption.Headers == null || corsOption.Headers.Count == 0) + { + builder.AllowAnyHeader(); + } + else + { + builder.WithMethods(corsOption.Headers.ToArray()); + } + + if (corsOption.ExposedHeaders != null && corsOption.ExposedHeaders.Count > 0) + { + builder.WithExposedHeaders(corsOption.ExposedHeaders.ToArray()); + } + + if (corsOption.AllowCredentials) + { + builder.AllowCredentials(); + } + else + { + builder.DisallowCredentials(); + } + + if (corsOption.PreflightMaxAge.TotalSeconds > 0) + { + builder.SetPreflightMaxAge(corsOption.PreflightMaxAge); + } + }); + }); + + return services; + } + + #endregion } } diff --git a/CorsServer/CorsServer.WebApi31/StartupConfig.cs b/CorsServer/CorsServer.WebApi31/StartupConfig.cs new file mode 100644 index 0000000..805b106 --- /dev/null +++ b/CorsServer/CorsServer.WebApi31/StartupConfig.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace CorsServer.WebApi31 +{ + public class StartupConfig + { + public StartupConfig(IConfiguration configuration, IHostEnvironment hostingEnvironment, IWebHostEnvironment webHostEnvironment) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + //Config + services.Configure(Configuration.GetSection("CORS")); + + //Corsļѡ + AddCors_Config(services); + + services.AddControllers(); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptionsSnapshot corsOtionsSnapshot) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseCors(CorsPolicyNameConst.DefaultPolicyName); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + + #region ע᲻ͬCors + + private IServiceCollection AddCors_Config(IServiceCollection services) + { + services.AddCors(setup => + { + var corsOption = services.BuildServiceProvider().GetRequiredService>().Value; + setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, builder => + { + if (corsOption.Origins == null) + { + builder.SetIsOriginAllowed(_ => true); + } + else if (corsOption.Origins.Count == 0) + { + builder.SetIsOriginAllowed(_ => true); + } + else if (corsOption.Origins.Contains("*")) + { + builder.SetIsOriginAllowed(_ => true); + } + else + { + builder.WithOrigins(corsOption.Origins.ToArray()); + builder.SetIsOriginAllowedToAllowWildcardSubdomains(); + } + + if (corsOption.Methods == null || corsOption.Methods.Count == 0) + { + builder.AllowAnyMethod(); + } + else + { + builder.WithMethods(corsOption.Methods.ToArray()); + } + + if (corsOption.Headers == null || corsOption.Headers.Count == 0) + { + builder.AllowAnyHeader(); + } + else + { + builder.WithMethods(corsOption.Headers.ToArray()); + } + + if (corsOption.ExposedHeaders != null && corsOption.ExposedHeaders.Count > 0) + { + builder.WithExposedHeaders(corsOption.ExposedHeaders.ToArray()); + } + + if (corsOption.AllowCredentials) + { + builder.AllowCredentials(); + } + else + { + builder.DisallowCredentials(); + } + + if (corsOption.PreflightMaxAge.TotalSeconds > 0) + { + builder.SetPreflightMaxAge(corsOption.PreflightMaxAge); + } + }); + }); + + return services; + } + + #endregion + } +} diff --git a/CorsServer/CorsServer.WebApi31/StartupDefaultPolicy.cs b/CorsServer/CorsServer.WebApi31/StartupDefaultPolicy.cs new file mode 100644 index 0000000..5070330 --- /dev/null +++ b/CorsServer/CorsServer.WebApi31/StartupDefaultPolicy.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace CorsServer.WebApi31 +{ + public class StartupDefaultPolicy + { + public StartupDefaultPolicy(IConfiguration configuration, IHostEnvironment hostingEnvironment, IWebHostEnvironment webHostEnvironment) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + //config + services.Configure(Configuration.GetSection("CORS")); + + //Cors + AddDefaultCors(services); + + services.AddControllers(); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptionsSnapshot corsOtionsSnapshot) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + //·ȫַǰ http://www.custom.com/PathBase/ + //app.UsePathBase("/api/"); + + app.UseRouting(); + + app.UseCors(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + + /// + /// ĬϲCors + /// + private IServiceCollection AddDefaultCors(IServiceCollection services) + { + services.AddCors(setupCors => + { + setupCors.AddDefaultPolicy(build => + { + build + .AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader() + .SetPreflightMaxAge(TimeSpan.FromMinutes(10)) + ; + }); + }); + + return services; + } + } +} diff --git a/CorsServer/CorsServer.WebApi31/appsettings.json b/CorsServer/CorsServer.WebApi31/appsettings.json index 7013fb5..bc33d6e 100644 --- a/CorsServer/CorsServer.WebApi31/appsettings.json +++ b/CorsServer/CorsServer.WebApi31/appsettings.json @@ -4,7 +4,9 @@ "Origins": ["*"], "Methods": [ "*" ], "Headers": [ "*" ], - "ExposedHeaders": ["x-custom-error"] + "AllowCredentials": false, + "ExposedHeaders": [ "x-custom-error" ], + "PreflightMaxAge": "00:20:30" }, "Logging": { "LogLevel": {