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);
        }
示例#2
0
        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());
        }
示例#3
0
        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(','));
            }
        }
示例#4
0
        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);
            }
        }
示例#5
0
        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();
        }
示例#6
0
        public static void SetupCors(this IServiceCollection services, IConfiguration configuration)
        {
            if (!configuration.GetValue <bool>("CorsEnabled"))
            {
                return;
            }

            var corsPolicies = configuration.GetSection("CorsPolicies");

            if (corsPolicies.GetChildren().All(section => section.Key != KEYS_POLICY_NAME))
            {
                services.AddCors(options => options.AddPolicy(KEYS_POLICY_NAME,
                                                              builder => builder
                                                              .AllowCredentials()
                                                              .AllowAnyHeader()
                                                              .AllowAnyMethod()
                                                              .AllowAnyOrigin()
                                                              ));
            }

            foreach (var policyConfiguration in corsPolicies.GetChildren())
            {
                var headers        = policyConfiguration.GetSection("Headers").Value?.Split(',');
                var methods        = policyConfiguration.GetSection("Methods").Value?.Split(',');
                var origins        = policyConfiguration.GetSection("Origins").Value?.Split(',');
                var exposedHeaders = policyConfiguration.GetSection("ExposedHeaders").Value?.Split(',');

                if (methods == null || origins == null)
                {
                    throw new InvalidOperationException(
                              $"Missing configuration fields for {policyConfiguration.Key}, please specify Headers, Methods, Origins and ExposedHeaders");
                }

                var policyBuilder = new CorsPolicyBuilder(origins);
                policyBuilder
                .WithHeaders(headers ?? new string[] { })
                .WithMethods(methods)
                .WithExposedHeaders(exposedHeaders ?? new string[] { });

                if (policyConfiguration.GetValue <bool>("AllowCredentials"))
                {
                    policyBuilder.AllowCredentials();
                }
                else
                {
                    policyBuilder.DisallowCredentials();
                }

                var maxPreflightAge = policyConfiguration.GetValue <double>("MaxPreflightAge");
                if (maxPreflightAge != 0)
                {
                    policyBuilder.SetPreflightMaxAge(TimeSpan.FromSeconds(maxPreflightAge));
                }

                services.AddCors(options => options.AddPolicy(policyConfiguration.Key, policyBuilder.Build()));
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)


        {
            services.AddSingleton(_config);

            //services.AddStormpath();
            //  services.AddScoped<TokenProviderMiddleware>();

            services.AddIdentity <ProductUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail         = true;
                config.Password.RequiredLength         = 4;
                config.Password.RequireDigit           = true;
                config.Password.RequireNonAlphanumeric = true;

                //  config.Cookies.ApplicationCookie.LoginPath
            })
            .AddEntityFrameworkStores <ProductContext>();

            services.AddLogging();

            services.AddDbContext <ProductContext>();
            services.AddScoped <IProductRepository, ProductRepository>();
            services.AddScoped <ProductContext>();

            //services.AddCors(options => options.AddPolicy("AllowAll", x => x.AllowAnyOrigin()));
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                                  builder => builder.WithOrigins("http://localhost:3000/"));
            });


            // Define CORS Policy
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.WithHeaders("*");
            corsBuilder.AllowAnyMethod();
            corsBuilder.WithOrigins("http://localhost:3000");
            //corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            corsBuilder.WithExposedHeaders().AllowAnyHeader();
            corsBuilder.SetPreflightMaxAge(TimeSpan.FromSeconds(30));

            services.AddCors(options =>
            {
                options.AddPolicy("localhost", corsBuilder.Build());
            });



            // services.AddTransient<ProductContextSeedData>();
            services.AddMvc();
        }
 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="headers"/> using <paramref name="policyBuilder"/> when
 /// <paramref name="allowAnyHeader"/> equals <see langword="false"/>.
 /// In another case, allows any header using <paramref name="policyBuilder"/>.
 /// </summary>
 /// <param name="policyBuilder"></param>
 /// <param name="allowAnyHeader"></param>
 /// <param name="headers"></param>
 private static void SetHeaders(CorsPolicyBuilder policyBuilder, bool allowAnyHeader, string[] headers)
 {
     if (allowAnyHeader)
     {
         policyBuilder.AllowAnyHeader();
     }
     else
     {
         policyBuilder.WithHeaders(headers);
     }
 }
        /// <summary>Set Allowed Headers</summary>
        /// <param name="builder">Cors policy builder configuration</param>
        /// <param name="itemCorsSection">Item configuration</param>
        private void SetAllowedHeaders(CorsPolicyBuilder builder, IConfiguration itemCorsSection)
        {
            var headers = itemCorsSection.GetSection("headers").Get <string[]>();

            if (headers != null)
            {
                builder.WithHeaders(headers);
            }
            else
            {
                builder.AllowAnyHeader();
            }
        }
示例#11
0
        // 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()));
        }
示例#13
0
    public void WithHeaders_AddsHeaders()
    {
        // Arrange
        var builder = new CorsPolicyBuilder();

        // Act
        builder.WithHeaders("example1", "example2");

        // Assert
        var corsPolicy = builder.Build();

        Assert.False(corsPolicy.AllowAnyHeader);
        Assert.Equal(new List <string>()
        {
            "example1", "example2"
        }, corsPolicy.Headers);
    }
示例#14
0
        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);
        }
示例#16
0
        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());
        }
示例#17
0
        private void BuildPolicies()
        {
            string content;

            using (var streamReader = new StreamReader(_fileProvider.GetFileInfo(_options.SettingsFileName).CreateReadStream()))
            {
                content = streamReader.ReadToEnd();
            }
            var policySettings = JsonConvert.DeserializeObject <IEnumerable <PolicySetting> >(content);

            var temp = new Dictionary <string, CorsPolicy>(StringComparer.OrdinalIgnoreCase);

            foreach (var policySetting in policySettings)
            {
                var corsPolicyBuilder = new CorsPolicyBuilder();
                if (policySetting.AllowedOrigins == null || policySetting.AllowedOrigins.Length == 0)
                {
                    corsPolicyBuilder.AllowAnyOrigin();
                }
                else
                {
                    corsPolicyBuilder.WithOrigins(policySetting.AllowedOrigins);
                }

                if (policySetting.AllowedHeaders == null || policySetting.AllowedHeaders.Length == 0)
                {
                    corsPolicyBuilder.AllowAnyHeader();
                }
                else
                {
                    corsPolicyBuilder.WithHeaders(policySetting.AllowedHeaders);
                }

                temp.Add(policySetting.Name, corsPolicyBuilder.Build());
            }

            // Delay 'updating' the policies as late as possible to prevent corrupting ongoing requests from
            // reading bad policy settings
            _policies = temp;

            _logger.LogInformation("Updated CORS policies");
        }
示例#18
0
        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();
            }
        }
示例#19
0
        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());
        }
示例#20
0
        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());
        }
示例#21
0
        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);
        }
示例#22
0
        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);
            }
        }
示例#23
0
 public static CorsPolicyBuilder WithFusionHeaders(this CorsPolicyBuilder builder)
 => builder
 .WithHeaders(FusionHeaders.RequestPublication)
 .WithExposedHeaders(FusionHeaders.Publication);
 public static void Apply(this CorsPolicyBuilder builder, CorsOption options)
 {
     builder.WithHeaders(options.AllowedHeaders).WithMethods(options.AllowedMethods).WithOrigins(options.AllowedHosts);
 }
        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);
        }
示例#26
0
        public void WithHeaders_AddsHeaders()
        {
            // Arrange
            var builder = new CorsPolicyBuilder();

            // Act
            builder.WithHeaders("example1", "example2");

            // Assert
            var corsPolicy = builder.Build();
            Assert.False(corsPolicy.AllowAnyHeader);
            Assert.Equal(new List<string>() { "example1", "example2" }, corsPolicy.Headers);
        }
示例#27
0
        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
    }
示例#28
0
        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);
            }
        }