private static CorsPolicyBuilder AddCorsConfiguration(this CorsPolicyBuilder builder, CorsPolicy configuration) { builder.WithOrigins(configuration.Origins); if (configuration.Methods?.Length > 0) { builder.WithMethods(configuration.Methods); } if (configuration.Headers?.Length > 0) { builder.WithMethods(configuration.Headers); } return(builder); }
public CorsPolicy Build() { CorsPolicyBuilder policy = new CorsPolicyBuilder(); ApplyAlls(); var origins = Origins.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); if (origins.Any()) { if (origins.First() == "*") { policy.AllowAnyOrigin(); } else { policy.WithOrigins(origins); } if (AllowCredentials && origins.First() != "*") { policy.AllowCredentials(); } else { policy.DisallowCredentials(); } } var methods = Methods.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); if (methods.Any()) { if (methods.First() == "*") { policy.AllowAnyMethod(); } else { policy.WithMethods(methods); } } var headers = Headers.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); if (headers.Any()) { if (headers.First() == "*") { policy.AllowAnyHeader(); } else { policy.WithHeaders(headers); } } policy.SetIsOriginAllowedToAllowWildcardSubdomains(); return(policy.Build()); }
public static IServiceCollection AddElectCors(this IServiceCollection services, [NotNull] Action <ElectCorsOptions> configuration) { services.Configure(configuration); var options = configuration.GetValue(); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.WithOrigins(options.AccessControlAllowOrigins.ToArray()); corsBuilder.WithHeaders(options.AccessControlAllowHeaders.ToArray()); corsBuilder.WithMethods(options.AccessControlAllowMethods.ToArray()); corsBuilder.AllowCredentials(); services.AddCors(config => { config.AddPolicy(options.PolicyName, corsBuilder.Build()); }); services.Configure <MvcOptions>(config => { config.Filters.Add(new CorsAuthorizationFilterFactory(options.PolicyName)); }); return(services); }
private static void InitCorsOptions(IConfiguration configuration, CorsPolicyBuilder policyBuilder) { string origins = configuration.GetValue <string>("Cors:origins"); string methods = configuration.GetValue <string>("Cors:methods"); string headers = configuration.GetValue <string>("Cors:headers"); if (origins == CorsConstants.AnyOrigin) { policyBuilder.AllowAnyOrigin(); } else { policyBuilder.WithOrigins(origins.Split(',')); } if (methods == "*") { policyBuilder.AllowAnyMethod(); } else { policyBuilder.WithMethods(methods.Split(',')); } if (headers == "*") { policyBuilder.AllowAnyHeader(); } else { policyBuilder.WithHeaders(headers.Split(',')); } }
public static void Configure(this CorsPolicyBuilder builder, CorsConfiguration configuration) { if (configuration.AllowedOrigins == null) { builder.AllowAnyOrigin(); } else { builder.WithOrigins(configuration.AllowedOrigins); } if (configuration.AllowedMethods == null) { builder.AllowAnyMethod(); } else { builder.WithMethods(configuration.AllowedMethods); } if (configuration.AllowedHeaders == null) { builder.AllowAnyHeader(); } else { builder.WithHeaders(configuration.AllowedHeaders); } }
public void Configure(CorsPolicyBuilder options, IServiceCollection services) { var settings = new ServiceSettings().Auth; options.WithOrigins(settings.ValidAuthReferrers); options.WithHeaders("X-Requested-With", "Content-Type"); options.WithMethods("POST"); options.AllowCredentials(); }
internal static void AddCORS(CorsPolicyBuilder builder, Configuration configData) { if (!string.IsNullOrEmpty(configData.AllowedOrigins)) { if (configData.AllowedOrigins == "*") { builder.AllowAnyOrigin(); } else { var allowedOrigins = configData.AllowedOrigins.Split(",", StringSplitOptions.RemoveEmptyEntries); builder.WithOrigins(allowedOrigins); } } if (!string.IsNullOrEmpty(configData.AllowedMethods)) { if (configData.AllowedMethods == "*") { builder.AllowAnyMethod(); } else { var allowedMethods = configData.AllowedMethods.Split(",", StringSplitOptions.RemoveEmptyEntries); builder.WithMethods(allowedMethods); } } if (!string.IsNullOrEmpty(configData.AllowedHeaders)) { if (configData.AllowedHeaders == "*") { builder.AllowAnyHeader(); } else { var allowedHeaders = configData.AllowedHeaders.Split(",", StringSplitOptions.RemoveEmptyEntries); builder.WithHeaders(allowedHeaders); } } if (!string.IsNullOrEmpty(configData.AllowedExposedHeaders)) { var allowedExposedHeaders = configData.AllowedExposedHeaders.Split(",", StringSplitOptions.RemoveEmptyEntries); if (allowedExposedHeaders.Any()) { builder.WithExposedHeaders(allowedExposedHeaders); } } if (configData.IsAllowedCredentials && configData.AllowedOrigins != "*") { builder.AllowCredentials(); } else { builder.DisallowCredentials(); } }
/// <summary> /// Adds the specified <paramref name="methods"/> using <paramref name="policyBuilder"/> when /// <paramref name="allowAnyMethod"/> equals <see langword="false"/>. /// In another case, allows any method using <paramref name="policyBuilder"/>. /// </summary> /// <param name="policyBuilder"></param> /// <param name="allowAnyMethod"></param> /// <param name="methods"></param> private static void SetMethods(CorsPolicyBuilder policyBuilder, bool allowAnyMethod, string[] methods) { if (allowAnyMethod) { policyBuilder.AllowAnyMethod(); } else { policyBuilder.WithMethods(methods); } }
/// <summary>Set Allowed Methods</summary> /// <param name="builder">Cors policy builder configuration</param> /// <param name="itemCorsSection">Item configuration</param> private void SetAllowedMethods(CorsPolicyBuilder builder, IConfiguration itemCorsSection) { var methods = itemCorsSection.GetSection("methods").Get <string[]>(); if (methods != null) { builder.WithMethods(methods); } else { builder.AllowAnyMethod(); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.WithHeaders("*"); corsBuilder.WithMethods("*"); corsBuilder.WithOrigins("*"); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); // Add framework services. services.AddMvc().AddJsonOptions(a => a.SerializerSettings.ContractResolver = new DefaultContractResolver());; }
public Task <CorsPolicy> GetPolicyAsync(HttpContext context, string policyName) { var originHeader = context.Request.Headers["Origin"].FirstOrDefault(); // unknown policy name or origin header not present: default behavior if (string.IsNullOrEmpty(policyName) || string.IsNullOrEmpty(originHeader) || !string.Equals(policyName, DefaultSenseNetCorsPolicyName, StringComparison.InvariantCultureIgnoreCase) || string.Equals(originHeader, "null", StringComparison.InvariantCultureIgnoreCase)) { return(Task.FromResult(_options.GetPolicy(policyName ?? _options.DefaultPolicyName))); } var policyBuilder = new CorsPolicyBuilder(); // Load current CORS settings from the repository. This must not be cached here, // because settings may change at runtime, anytime. var corsSettings = Settings.GetValue <IEnumerable <string> >(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_ALLOWEDORIGINDOMAINS, null, SnCorsConstants.DefaultAllowedDomains); // get a configured domain (or template) that matches the origin sent by the client var allowedDomain = GetAllowedDomain(originHeader, corsSettings); if (!string.IsNullOrEmpty(allowedDomain)) { // template match: set the allowed origin policyBuilder.WithOrigins(originHeader); // any origin ('*') and credentials are mutually exclusive if (!string.Equals(originHeader, CorsConstants.AnyOrigin)) { policyBuilder.AllowCredentials(); } var allowedMethods = Settings.GetValue(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_ALLOWEDMETHODS, null, SnCorsConstants.AccessControlAllowMethodsDefault); var allowedHeaders = Settings.GetValue(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_ALLOWEDHEADERS, null, SnCorsConstants.AccessControlAllowHeadersDefault); policyBuilder.WithMethods(allowedMethods); policyBuilder.WithHeaders(allowedHeaders); } return(Task.FromResult(policyBuilder.Build())); }
public void WithMethods_AddsMethods() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithMethods("PUT", "GET"); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyOrigin); Assert.Equal(new List <string>() { "PUT", "GET" }, corsPolicy.Methods); }
public CorsPolicy Build() { CorsPolicyBuilder policy = new CorsPolicyBuilder(); if (this.AllowAnyOrigin) { policy.AllowAnyOrigin(); } else { policy.WithOrigins(this.Origins); } if (this.AllowAnyHeader) { policy.AllowAnyHeader(); } else { policy.WithHeaders(this.Headers); } if (this.AllowAnyMethod) { policy.AllowAnyMethod(); } else { policy.WithMethods(this.Methods); } if (this.SupportsCredentials) { policy.AllowCredentials(); } else { policy.DisallowCredentials(); } policy.WithExposedHeaders("content-disposition"); return(policy.Build()); }
/// <summary> /// Customizes cors cfg /// </summary> /// <param name="builder"></param> /// <returns></returns> public static CorsPolicyBuilder CustomizeCors(this CorsPolicyBuilder builder) { var cfg = Cartomatic.Utils.NetCoreConfig.GetNetCoreConfig(); var origins = cfg.GetSection("CorsCfg:Origins").Get <string[]>() ?? new string[0]; var headers = cfg.GetSection("CorsCfg:Headers").Get <string[]>() ?? new string[0]; var methods = cfg.GetSection("CorsCfg:Methods").Get <string[]>() ?? new string[0]; //all origins allowed if (origins.Any(o => o == "*")) { builder.AllowAnyOrigin(); } else if (origins.Any()) { if (origins.Any(o => o.IndexOf("*") > -1)) { builder.SetIsOriginAllowedToAllowWildcardSubdomains(); } builder.WithOrigins(origins); } if (headers.Any(h => h == "*")) { builder.AllowAnyHeader(); } else if (headers.Any()) { builder.WithHeaders(headers); } if (methods.Any(m => m == "*")) { builder.AllowAnyMethod(); } else if (methods.Any()) { builder.WithMethods(methods); } return(builder); }
public CorsPolicy Build() { var policy = new CorsPolicyBuilder(); if (this.AllowAnyOrigin) { policy.AllowAnyOrigin(); } else { policy.WithOrigins(this.Origins); } if (this.AllowAnyHeader) { policy.AllowAnyHeader(); } else { policy.WithHeaders(this.Headers); } if (this.AllowAnyMethod) { policy.AllowAnyMethod(); } else { policy.WithMethods(this.Methods); } if (this.SupportsCredentials) { policy.AllowCredentials(); } else { policy.DisallowCredentials(); } return(policy.Build()); }
private static void AddPolicy(CorsPolicyBuilder policyBuilder, CorsPolicyConfiguration policy) { if (policy.Origins.Length == 0) { throw new System.ArgumentException(); } policyBuilder.WithOrigins(policy.Origins); // Configure methods if (policy.Methods.Length == 0) { policyBuilder.AllowAnyMethod(); } else { policyBuilder.WithMethods(policy.Methods); } // Configure headers if (policy.Headers.Length == 0) { policyBuilder.AllowAnyHeader(); } else { policyBuilder.WithHeaders(policy.Headers); } //Configure credentials if (policy.AllowCredentials) { policyBuilder.AllowCredentials(); } else { policyBuilder.DisallowCredentials(); } }
public CorsPolicy Build() { CorsPolicyBuilder policy = new CorsPolicyBuilder(); if (Origins.IsEmpty()) { policy.AllowAnyOrigin(); } else { policy.WithOrigins(Origins); } if (Methods.IsEmpty()) { policy.AllowAnyMethod(); } else { policy.WithMethods(Origins); } if (Headers.IsEmpty()) { policy.AllowAnyHeader(); } else { policy.WithHeaders(Origins); } if (AllowCredentials) { policy.AllowCredentials(); } else { policy.DisallowCredentials(); } return(policy.Build()); }
public CorsPolicy Build() { CorsPolicyBuilder policy = new CorsPolicyBuilder(); if (AllowAnyOrigin) { policy.AllowAnyOrigin(); } else { policy.WithOrigins(Origins); } if (AllowAnyMethod) { policy.AllowAnyMethod(); } else { policy.WithMethods(Origins); } if (AllowAnyHeader) { policy.AllowAnyHeader(); } else { policy.WithHeaders(Origins); } if (AllowCredentials && Origins?.Length > 0) { policy.AllowCredentials(); } else { policy.DisallowCredentials(); } return(policy.Build()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddEntityFrameworkNpgsql().AddDbContext <EstabelecimentoContext>(options => options.UseNpgsql(Configuration.GetConnectionString("EstabelecimentosDB"))); // Add framework services. services.AddMvc(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("SiteCorsPolicy")); }); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.WithMethods("GET").WithMethods("POST").WithMethods("DELETE").WithMethods("PUT"); corsBuilder.AllowAnyOrigin(); // For anyone access. corsBuilder.WithOrigins("http://localhost:4200", "http://localhost", "http://localhost:4200"); // for a specific url. Don't add a forward slash on the end! corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); }
public static IServiceCollection AddCors(this IServiceCollection services, IConfiguration configuration, string configSection = DefaultConfigSection) { configuration.BuildCrosConfig(configSection); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.WithOrigins(CrosConfig.AccessControlAllowOrigin.Split(',').Select(x => x?.Trim()).ToArray()); corsBuilder.WithHeaders(CrosConfig.AccessControlAllowHeaders.Split(',').Select(x => x?.Trim()).ToArray()); corsBuilder.WithMethods(CrosConfig.AccessControlAllowMethods.Split(',').Select(x => x?.Trim()).ToArray()); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy(CrosConfig.PolicyAllowAllName, corsBuilder.Build()); }); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory(CrosConfig.PolicyAllowAllName)); }); return(services); }
public void WithMethods_AddsMethods() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithMethods("PUT", "GET"); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyOrigin); Assert.Equal(new List<string>() { "PUT", "GET" }, corsPolicy.Methods); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region Framework Services // Add framework services. services.AddOptions(); services.AddApplicationInsightsTelemetry(Configuration); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(10); options.Cookie.HttpOnly = true; }); services.AddDbContext <ApplicationDbContext <User, Role, int> >(options => { options.UseSqlServer(_connectionString); // SQL SERVER // options.UseMySql(_connectionString); // My SQL }); services.AddIdentity <User, Role>(o => { o.Password.RequireDigit = false; o.Password.RequireUppercase = false; o.Password.RequireLowercase = false; o.Password.RequireNonAlphanumeric = false; o.User.RequireUniqueEmail = false; }).AddEntityFrameworkStores <ApplicationDbContext <User, Role, int> >() .AddDefaultTokenProviders(); services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.WithMethods("GET", "POST", "PUT", "DELETE"); corsBuilder.WithOrigins("*"); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("AllowCors", corsBuilder.Build()); }); services.Configure <FormOptions>(x => { x.ValueLengthLimit = int.MaxValue; x.MultipartBodyLengthLimit = int.MaxValue; x.KeyLengthLimit = int.MaxValue; }); services.AddMvc(); // enable JwT Token authentication for WEB API //services.AddAuthentication(options => //{ // options.DefaultAuthenticateScheme = "Jwt"; // options.DefaultChallengeScheme = "Jwt"; //}).AddJwtBearer("Jwt", options => //{ // options.TokenValidationParameters = new TokenValidationParameters // { // ValidateAudience = false, // //ValidAudience = "the audience you want to validate", // ValidateIssuer = false, // //ValidIssuer = "the isser you want to validate", // ValidateIssuerSigningKey = true, // IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtIssuerOptions:SecretKey"])), // ValidateLifetime = true, //validate the expiration and not before values in the token // ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date // }; //}); #endregion #region Our Services var cs = new ConnectionStringDto() { ConnectionString = _connectionString }; services.AddSingleton(cs); services.AddScoped <DbContext, ApplicationDbContext <User, Role, int> >(); services.AddScoped <DbContextOptions <ApplicationDbContext <User, Role, int> > >(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddTransient <IEmailSender, EmailSender>(); var mappingConfig = new AutoMapper.MapperConfiguration(cfg => { cfg.Mapping(services.BuildServiceProvider().GetService <UserManager <User> >()); }); services.AddSingleton(x => mappingConfig.CreateMapper()); services.AddScoped <IRepository <User>, EntityFrameworkRepository <User> >(); services.AddScoped <IRepository <Role>, EntityFrameworkRepository <Role> >(); services.AddScoped <IRepository <IdentityUserRole <int> >, EntityFrameworkRepository <IdentityUserRole <int> > >(); // >> KPA services.AddScoped <ICategoryService, CategoryService>(); // << KPA #endregion Services = services; }
private static void ConfigureCors(CorsPolicyBuilder policyBuilder) { policyBuilder.AllowAnyOrigin(); policyBuilder.AllowAnyHeader(); policyBuilder.WithMethods("GET", "POST"); }
private void BuildCorsPolicy(CorsPolicyBuilder builder) { CorsWhitelistModel model; string errorMessage = $"Ignoring invalid CORS whitelist: '{this.config.Global.ClientAuth.CorsWhitelist}'"; try { model = JsonConvert.DeserializeObject <CorsWhitelistModel>(this.config.Global.ClientAuth.CorsWhitelist); if (model == null) { this.logger.LogError(new Exception(errorMessage), errorMessage); return; } } catch (Exception ex) { this.logger.LogError(ex, errorMessage); return; } if (model.Origins == null) { this.logger.LogInformation("No setting for CORS origin policy was found, ignore"); } else if (model.Origins.Contains("*")) { this.logger.LogInformation("CORS policy allowed any origin"); builder.AllowAnyOrigin(); } else { this.logger.LogInformation("Add origins '{origins}' to CORS policy", model.Origins); builder.WithOrigins(model.Origins); } if (model.Origins == null) { this.logger.LogInformation("No setting for CORS method policy was found, ignore"); } else if (model.Methods.Contains("*")) { this.logger.LogInformation("CORS policy allowed any method"); builder.AllowAnyMethod(); } else { this.logger.LogInformation("Add methods '{methods}' to CORS policy", model.Methods); builder.WithMethods(model.Methods); } if (model.Origins == null) { this.logger.LogInformation("No setting for CORS header policy was found, ignore"); } else if (model.Headers.Contains("*")) { this.logger.LogInformation("CORS policy allowed any header"); builder.AllowAnyHeader(); } else { this.logger.LogInformation("Add headers '{headers}' to CORS policy", model.Headers); builder.WithHeaders(model.Headers); } }
public static IServiceCollection AddElectCors(this IServiceCollection services, [NotNull] Action <ElectCorsOptions> configuration) { services.Configure(configuration); var options = configuration.GetValue(); var corsBuilder = new CorsPolicyBuilder(); if (options.IsOriginAllowed != null) { corsBuilder.SetIsOriginAllowed(options.IsOriginAllowed); } else if (options.AllowOrigins?.Any() == true) { options.AllowOrigins = options.AllowOrigins.Distinct().OrderBy(x => x).ToList(); if (options.AllowOrigins.Contains("*")) { corsBuilder.SetIsOriginAllowed((origin) => true); } else { corsBuilder.WithOrigins(options.AllowOrigins.ToArray()); corsBuilder.SetIsOriginAllowedToAllowWildcardSubdomains(); } } if (options.AllowHeaders?.Any() == true) { if (options.AllowHeaders.Contains("*")) { corsBuilder.AllowAnyHeader(); } else { corsBuilder.WithHeaders(options.AllowHeaders.ToArray()); } } if (options.AllowMethods?.Any() == true) { if (options.AllowMethods.Contains("*")) { corsBuilder.AllowAnyMethod(); } else { corsBuilder.WithMethods(options.AllowMethods.ToArray()); } } if (options.IsAllowCredentials) { corsBuilder.AllowCredentials(); } else { corsBuilder.DisallowCredentials(); } options.ExtendPolicyBuilder?.Invoke(corsBuilder); services.AddCors(config => { config.DefaultPolicyName = options.PolicyName; config.AddDefaultPolicy(corsBuilder.Build()); options.ExtendPolicyOptions?.Invoke(config); }); services.Configure <MvcOptions>(config => { config.Filters.Add(new CorsAuthorizationFilterFactory(options.PolicyName)); }); services.TryAddTransient <CorsAuthorizationFilter, CorsAuthorizationFilter>(); return(services); }
public void Build(CorsPolicyBuilder options) { options.WithMethods("GET").WithOrigins(GetEnvOrigins()); }
private void BuildCorsPolicy(CorsPolicyBuilder builder) { CorsWhitelistModel model; try { model = JsonConvert.DeserializeObject <CorsWhitelistModel>(this.config.CorsWhitelist); if (model == null) { this.log.Error("Invalid CORS whitelist. Ignored", () => new { this.config.CorsWhitelist }); return; } } catch (Exception ex) { this.log.Error("Invalid CORS whitelist. Ignored", () => new { this.config.CorsWhitelist, ex.Message }); return; } if (model.Origins == null) { this.log.Info("No setting for CORS origin policy was found, ignore", () => { }); } else if (model.Origins.Contains("*")) { this.log.Info("CORS policy allowed any origin", () => { }); builder.AllowAnyOrigin(); } else { this.log.Info("Add specified origins to CORS policy", () => new { model.Origins }); builder.WithOrigins(model.Origins); } if (model.Origins == null) { this.log.Info("No setting for CORS method policy was found, ignore", () => { }); } else if (model.Methods.Contains("*")) { this.log.Info("CORS policy allowed any method", () => { }); builder.AllowAnyMethod(); } else { this.log.Info("Add specified methods to CORS policy", () => new { model.Methods }); builder.WithMethods(model.Methods); } if (model.Origins == null) { this.log.Info("No setting for CORS header policy was found, ignore", () => { }); } else if (model.Headers.Contains("*")) { this.log.Info("CORS policy allowed any header", () => { }); builder.AllowAnyHeader(); } else { this.log.Info("Add specified headers to CORS policy", () => new { model.Headers }); builder.WithHeaders(model.Headers); } }
public virtual async Task <CorsPolicy> GetPolicyAsync(HttpContext context, string policyName) { ICorsPolicy[] loadedCorsPolicies = null; // Find cors policies manager. var corsPoliciesManager = context.RequestServices.GetService <ISiteCorsPolicyService>(); if (corsPoliciesManager == null) { throw new ArgumentException($"{nameof(ISiteCorsPolicyService)} is not found in service context."); } // Policy name is defined, find the entity. if (!string.IsNullOrWhiteSpace(policyName)) { var loadedCorsPolicy = await corsPoliciesManager.GetCorsPolicyAsync(policyName); if (loadedCorsPolicy != null) { loadedCorsPolicies = new[] { loadedCorsPolicy } } ; } else { loadedCorsPolicies = await corsPoliciesManager.GetInUseCorsPoliciesAsync(); } if (loadedCorsPolicies == null || loadedCorsPolicies.Length < 1) { return(null); } var appliedCorsPolicyBuilder = new CorsPolicyBuilder(); foreach (var loadedCorsPolicy in loadedCorsPolicies) { var allowedHeaders = loadedCorsPolicy.AllowedHeaders; if (allowedHeaders != null && allowedHeaders.Length > 0) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.WithHeaders(allowedHeaders); } var allowedOrigins = loadedCorsPolicy.AllowedOrigins; if (allowedOrigins != null && allowedOrigins.Length > 0) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.WithOrigins(allowedOrigins); } var allowedMethods = loadedCorsPolicy.AllowedMethods; if (allowedMethods != null && allowedMethods.Length > 0) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.WithMethods(allowedMethods); } var allowedExposedHeaders = loadedCorsPolicy.AllowedExposedHeaders; if (allowedExposedHeaders != null && allowedExposedHeaders.Length > 0) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.WithExposedHeaders(allowedExposedHeaders); } if (loadedCorsPolicy.AllowCredential) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.AllowCredentials(); } } var builtPolicy = appliedCorsPolicyBuilder .Build(); return(builtPolicy); } #endregion }