public CorsPolicyProvider(CorsPolicy policy, IEnumerable<string> allowedPaths)
        {
            if (policy == null) throw new ArgumentNullException("policy");
            if (allowedPaths == null) throw new ArgumentNullException("allowedPaths");

            this.policy = policy;
            this.paths = allowedPaths.Select(path => Normalize(path)).ToArray();
        }
예제 #2
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services) {
     services.AddEntityFramework().AddDbContext<SplendorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SplendorContext")));
     var policy = new CorsPolicy();
     policy.Headers.Add("*");
     policy.Methods.Add("*");
     policy.Origins.Add("*");
     services.AddCors(options => options.AddPolicy("AllowSpecificOrigin", policy));
     services.AddMvc();
 }
예제 #3
0
 public void SettingNegativePreflightMaxAge_Throws()
 {
     CorsPolicy corsPolicy = new CorsPolicy();
     Assert.ThrowsArgumentOutOfRange(() =>
     {
         corsPolicy.PreflightMaxAge = -2;
     },
     "value",
     "PreflightMaxAge must be greater than or equal to 0.");
 }
        public void EvaluatePolicy_EmptyOriginsPolicy_ReturnsInvalidResult()
        {
            CorsEngine corsEngine = new CorsEngine();
            CorsRequestContext requestContext = new CorsRequestContext
            {
                Origin = "foo"
            };
            CorsPolicy policy = new CorsPolicy();

            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);

            Assert.False(result.IsValid);
            Assert.Contains("The origin 'foo' is not allowed.", result.ErrorMessages);
        }
예제 #5
0
        public void Default_Constructor()
        {
            CorsPolicy corsPolicy = new CorsPolicy();

            Assert.False(corsPolicy.AllowAnyHeader);
            Assert.False(corsPolicy.AllowAnyMethod);
            Assert.False(corsPolicy.AllowAnyOrigin);
            Assert.False(corsPolicy.SupportsCredentials);
            Assert.Empty(corsPolicy.ExposedHeaders);
            Assert.Empty(corsPolicy.Headers);
            Assert.Empty(corsPolicy.Methods);
            Assert.Empty(corsPolicy.Origins);
            Assert.Null(corsPolicy.PreflightMaxAge);
        }
예제 #6
0
        public void SettingNegativePreflightMaxAge_Throws()
        {
            // Arrange
            var policy = new CorsPolicy();

            // Act
            var exception = Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                policy.PreflightMaxAge = TimeSpan.FromSeconds(-12);
            });

            // Assert
            Assert.Equal(
                $"PreflightMaxAge must be greater than or equal to 0.{Environment.NewLine}Parameter name: value",
                exception.Message);
        }
예제 #7
0
        public void ToString_ReturnsThePropertyValues()
        {
            CorsPolicy corsPolicy = new CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyOrigin = true,
                PreflightMaxAge = 10,
                SupportsCredentials = true
            };
            corsPolicy.Headers.Add("foo");
            corsPolicy.Headers.Add("bar");
            corsPolicy.Origins.Add("http://example.com");
            corsPolicy.Origins.Add("http://example.org");
            corsPolicy.Methods.Add("GET");

            Assert.Equal(@"AllowAnyHeader: True, AllowAnyMethod: False, AllowAnyOrigin: True, PreflightMaxAge: 10, SupportsCredentials: True, Origins: {http://example.com,http://example.org}, Methods: {GET}, Headers: {foo,bar}, ExposedHeaders: {}", corsPolicy.ToString());
        }
예제 #8
0
        public static void RegisterCors(this IAppBuilder app)
        {
            var corsPolicy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true,
                AllowAnyOrigin = true
            };

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            };

            app.UseCors(corsOptions);
        }
        private void ConfigureCors(IAppBuilder app)
        {
            var politica = new CorsPolicy();

            politica.AllowAnyHeader = true;
            politica.Origins.Add("http://localhost:50080");
            politica.Methods.Add("GET");
            politica.Methods.Add("POST");

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(politica)
                }
            };

            app.UseCors(corsOptions);
        }
예제 #10
0
        public void SendAsync_ReturnsAllowAOrigin(string requestOrigin, string policyOrigin, string expectedOrigin)
        {
            IAppBuilder builder = new AppBuilder();
            var         policy  = new CorsPolicy();

            if (policyOrigin == "*")
            {
                policy.AllowAnyOrigin = true;
            }
            else
            {
                foreach (var o in policyOrigin.Split(','))
                {
                    policy.Origins.Add(o.Trim());
                }
            }

            builder.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(policy)
                }
            });

            builder.Use((context, next) => Task.FromResult <object>(null));

            var app = (AppFunc)builder.Build(typeof(AppFunc));

            IOwinRequest request = CreateRequest("http://localhost/sample");

            if ("header_not_set" != requestOrigin)
            {
                request.Headers.Set(CorsConstants.Origin, requestOrigin);
            }
            app(request.Environment).Wait();

            var    response = new OwinResponse(request.Environment);
            string origin   = response.Headers.Get("Access-Control-Allow-Origin");

            Assert.Equal(200, response.StatusCode);
            Assert.Equal(expectedOrigin, origin);
        }
        public async Task GetsNamedPolicy(string policyName)
        {
            // Arrange
            var options = new CorsOptions();
            var policy = new CorsPolicy();
            options.AddPolicy(policyName, policy);

            var corsOptions = new TestCorsOptions
            {
                Value = options
            };
            var policyProvider = new DefaultCorsPolicyProvider(corsOptions);

            // Act 
            var actualPolicy = await policyProvider.GetPolicyAsync(new DefaultHttpContext(), policyName);

            // Assert
            Assert.Same(policy, actualPolicy);
        }
예제 #12
0
        public void EvaluatePolicy_PreflightRequest_AnyMethod_ReturnsRequestMethod()
        {
            CorsEngine         corsEngine     = new CorsEngine();
            CorsRequestContext requestContext = new CorsRequestContext
            {
                HttpMethod = "OPTIONS",
                AccessControlRequestMethod = "GET",
                Origin = "foo"
            };
            CorsPolicy policy = new CorsPolicy {
                AllowAnyOrigin = true, AllowAnyMethod = true
            };

            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);

            Assert.True(requestContext.IsPreflight);
            Assert.Equal(1, result.AllowedMethods.Count);
            Assert.Contains("GET", result.AllowedMethods);
        }
예제 #13
0
        /// <summary>
        /// Initializes and configures <see cref="CorsOptions"/> instance.
        /// </summary>
        public static void Configure()
        {
            var corsPolicy = new CorsPolicy
            {
                AllowAnyMethod      = true,
                AllowAnyHeader      = true,
                SupportsCredentials = ApiSettings.CorsSupportsCredentials
            };

            AddOrigins(corsPolicy, ApiSettings.CorsOrigins);

            Options = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            };
        }
예제 #14
0
        public Task <CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var corsRequestContext = request.GetCorsRequestContext();
            var originRequested    = corsRequestContext.Origin;

            string approvedOrigin = AllowedCorsOrigin(originRequested);

            if (String.IsNullOrWhiteSpace(approvedOrigin))
            {
                return(Task.FromResult <CorsPolicy>(null));
            }

            // Grant CORS request
            var policy = new CorsPolicy
            {
                AllowAnyHeader      = true,
                AllowAnyMethod      = true,
                SupportsCredentials = true,
            };

            // add headers
            policy.Headers.Add("content-type");
            policy.Headers.Add("withcredentials");
            policy.Headers.Add("Access-Control-Allow-Headers");
            policy.Headers.Add("Access-Control-Allow-Origin");
            policy.Headers.Add("Origin");
            policy.Headers.Add("Accept");
            policy.Headers.Add("X-Requested-With");
            policy.Headers.Add("Access-Control-Request-Method");
            policy.Headers.Add("Access-Control-Request-Headers");

            if (approvedOrigin == "*")
            {
                policy.AllowAnyOrigin = true;
            }
            else
            {
                policy.AllowAnyOrigin = false;
                policy.Origins.Add(approvedOrigin);
            }

            return(Task.FromResult(policy));
        }
        public async Task GetsNamedPolicy(string policyName)
        {
            // Arrange
            var options = new CorsOptions();
            var policy = new CorsPolicy();
            options.AddPolicy(policyName, policy);

            var mockOptions = new Mock<IOptions<CorsOptions>>();
            mockOptions
                .SetupGet(o => o.Options)
                .Returns(options);
            var policyProvider = new DefaultCorsPolicyProvider(mockOptions.Object);

            // Act 
            var actualPolicy = await policyProvider.GetPolicyAsync(new DefaultHttpContext(), policyName);

            // Assert
            Assert.Same(policy, actualPolicy);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            // ===== Add Jwt Authentication ========
            services.AddCors(config =>
            {
                var policy = new CorsPolicy();
                policy.Headers.Add("*");
                policy.Methods.Add("*");
                policy.Origins.Add("*");
                policy.SupportsCredentials = true;
                config.AddPolicy("policy", policy);
            });


            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser().Build());
            });

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = new RsaSecurityKey(new RSACryptoServiceProvider(2048).ExportParameters(true)),
                    ValidAudience            = "Audience",
                    ValidIssuer              = "Issuer",
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.FromMinutes(0)
                };
            });

            services.AddTransient <JwtHelper, JwtHelper>();
            services.AddTransient <ConfigurationHelper, ConfigurationHelper>();
        }
예제 #17
0
        public EdartiCorsPolicyAttribute()
        {
            _policy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true,
            };

            var whiteLists = ConfigurationManager.AppSettings[keyCorsAllowOrigin];

            if (!string.IsNullOrEmpty(whiteLists))
            {
                foreach (var origin in from v in whiteLists.Split(';')
                         where !string.IsNullOrEmpty(v)
                         select v)
                {
                    _policy.Origins.Add(origin.Trim());
                }
            }
        }
예제 #18
0
 public TCCorsPolicyProvider()
 {
     _policy = new CorsPolicy
     {
         SupportsCredentials = true,
         AllowAnyHeader      = true,
         AllowAnyMethod      = true,
         AllowAnyOrigin      = true
     };
     //string[] allowedOrigins = "john.doe,ava.wise".Split(',');
     //string[] allowedMethods = "GET,POST,PUT,OPTIONS".Split(',');
     //string[] allowedHeaders = "Content-Type,Origin,Authorization,Accept".Split(',');
     //// Add allowed origins.
     //foreach (string origin in allowedOrigins)
     //    _policy.Origins.Add(origin);
     //foreach (string method in allowedMethods)
     //    _policy.Methods.Add(method);
     //foreach (string header in allowedHeaders)
     //    _policy.Headers.Add(header);
 }
        public WebConfigCorsPolicyProvider()
        {
            // Create a CORS policy.
            _policy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true
            };

            var origins = ConfigurationManager.AppSettings[CorsDomainKey];

            if (string.IsNullOrEmpty(origins))
            {
                throw new InvalidOperationException("No Cors configuration especified in the web.config");
            }

            var corsDomain = origins.Split(',').ToList();

            corsDomain.ForEach(_policy.Origins.Add);
        }
예제 #20
0
        public void EvaluatePolicy_PreflightRequest_OriginAllowed_ReturnsOrigin()
        {
            CorsEngine         corsEngine     = new CorsEngine();
            CorsRequestContext requestContext = new CorsRequestContext
            {
                HttpMethod = "OPTIONS",
                AccessControlRequestMethod = "PUT",
                Origin = "foo"
            };
            CorsPolicy policy = new CorsPolicy {
                AllowAnyMethod = true
            };

            policy.Origins.Add("foo");

            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);

            Assert.True(requestContext.IsPreflight);
            Assert.Equal("foo", result.AllowedOrigin);
        }
예제 #21
0
        private async Task <CorsPolicy> GetCorsPolicyAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken
            )
        {
            CorsPolicy corsPolicy = null;
            ICorsPolicyProviderFactory corsPolicyProviderFactory =
                _httpConfiguration.GetCorsPolicyProviderFactory();
            ICorsPolicyProvider corsPolicyProvider =
                corsPolicyProviderFactory.GetCorsPolicyProvider(request);

            if (corsPolicyProvider != null)
            {
                corsPolicy = await corsPolicyProvider.GetCorsPolicyAsync(
                    request,
                    cancellationToken
                    );
            }
            return(corsPolicy);
        }
예제 #22
0
        public static IAppBuilder UseCors(this IAppBuilder app, CorsConfiguration appSettings)
        {
            var corsPolicy = new CorsPolicy
            {
                SupportsCredentials = true
            };

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(
                        corsPolicy.AddHeaders(appSettings.Headers)
                        .AddMethods(appSettings.Methods)
                        .AddOrigins(appSettings.Origins))
                }
            };

            return(app.UseCors(corsOptions));
        }
예제 #23
0
        public async Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var corsRequestContext = request.GetCorsRequestContext();
            var originRequested = corsRequestContext.Origin;

            if (await IsOriginFromCustomer(originRequested))
            {
                var policy = new CorsPolicy
                {
                    AllowAnyHeader = true,
                    AllowAnyMethod = true
                };
                policy.Origins.Add(originRequested);

                //IP ESPECIFICA
                //policy.Origins.Add("http://localhost:56360");
                return policy;
            }
            return null;
        }
예제 #24
0
파일: Startup.cs 프로젝트: hodoje/web
        public void Configuration(IAppBuilder app)
        {
            //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var corsPolicy = new CorsPolicy
            {
                AllowAnyHeader      = true,
                AllowAnyMethod      = true,
                SupportsCredentials = true
            };

            corsPolicy.Origins.Add("http://localhost:4200");
            app.UseCors(new CorsOptions()
            {
                PolicyProvider = new CorsPolicyProvider()
                {
                    PolicyResolver = r => Task.FromResult(corsPolicy)
                }
            });
            app.MapSignalR();
        }
예제 #25
0
    private bool IsOriginAllowed(CorsPolicy policy, StringValues origin)
    {
        if (StringValues.IsNullOrEmpty(origin))
        {
            _logger.RequestDoesNotHaveOriginHeader();
            return(false);
        }

        var originString = origin.ToString();

        _logger.RequestHasOriginHeader(originString);
        if (policy.AllowAnyOrigin || policy.IsOriginAllowed(originString))
        {
            _logger.PolicySuccess();
            return(true);
        }
        _logger.PolicyFailure();
        _logger.OriginNotAllowed(originString);
        return(false);
    }
예제 #26
0
        public void CrearCors(IAppBuilder app)
        {
            var policy = new CorsPolicy
            {
                AllowAnyHeader      = true,
                AllowAnyMethod      = true,
                AllowAnyOrigin      = true,
                SupportsCredentials = true
            };

            policy.ExposedHeaders.Add("X-Custom-Header");

            app.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = Context => Task.FromResult(policy)
                }
            });
        }
예제 #27
0
        public async Task <CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var corsRequestContext = request.GetCorsRequestContext();
            var originRequestd     = corsRequestContext.Origin;

            if (await IsOriginFromCustomer(originRequestd))
            {
                var policy = new CorsPolicy
                {
                    AllowAnyHeader = true,
                    AllowAnyMethod = true
                };

                policy.Origins.Add(originRequestd);

                return(policy);
            }

            return(null);
        }
예제 #28
0
    public void EvaluatePolicy_CaseInsensitivePreflightRequest_ReturnsAllowedMethods(string method)
    {
        // Arrange
        var corsService    = GetCorsService();
        var requestContext = GetHttpContext(
            method: "OPTIONS",
            origin: "http://example.com",
            accessControlRequestMethod: method);
        var policy = new CorsPolicy();

        policy.Origins.Add(CorsConstants.AnyOrigin);
        policy.Methods.Add("PUT");
        policy.Methods.Add("DELETE");

        // Act
        var result = corsService.EvaluatePolicy(requestContext, policy);

        // Assert
        Assert.Equal(new[] { "PUT", "DELETE" }, result.AllowedMethods);
    }
예제 #29
0
        private CorsPolicy GetCorsPolicy()
        {
            var policy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true,
            };
            var corsOrigins = ConfigurationManager.AppSettings["CorsOrigins"];

            if (string.IsNullOrEmpty(corsOrigins))
            {
                return(policy);
            }

            foreach (var origin in corsOrigins.Split(';'))
            {
                policy.Origins.Add(origin);
            }
            return(policy);
        }
예제 #30
0
    public void EvaluatePolicy_CaseInsensitivePreflightRequest_OriginAllowed_ReturnsOrigin(string preflightMethod)
    {
        // Arrange
        var corsService    = GetCorsService();
        var requestContext = GetHttpContext(
            method: preflightMethod,
            origin: "http://example.com",
            accessControlRequestMethod: "PUT");
        var policy = new CorsPolicy();

        policy.Origins.Add(CorsConstants.AnyOrigin);
        policy.Origins.Add("http://example.com");
        policy.Methods.Add("*");

        // Act
        var result = corsService.EvaluatePolicy(requestContext, policy);

        // Assert
        Assert.Equal("http://example.com", result.AllowedOrigin);
    }
        public ConfigurableCorsPolicyAttribute(string name)
        {
            _policy = new CorsPolicy();

            var config     = ConfigurationManager.GetSection("cors");
            var corsConfig = (CorsSection)config;

            if (corsConfig != null)
            {
                var policy = corsConfig.CorsPolicies.Cast <CorsElement>().FirstOrDefault(x => x.Name == name);
                if (policy != null)
                {
                    if (policy.Headers == "*")
                    {
                        _policy.AllowAnyHeader = true;
                    }
                    else
                    {
                        policy.Headers.Split(';').ToList().ForEach(x => _policy.Headers.Add(x));
                    }

                    if (policy.Methods == "*")
                    {
                        _policy.AllowAnyMethod = true;
                    }
                    else
                    {
                        policy.Methods.Split(';').ToList().ForEach(x => _policy.Methods.Add(x));
                    }

                    if (policy.Origins == "*")
                    {
                        _policy.AllowAnyOrigin = true;
                    }
                    else
                    {
                        policy.Origins.Split(';').ToList().ForEach(x => _policy.Origins.Add(x));
                    }
                }
            }
        }
예제 #32
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <IdentityUser>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddCors(config =>
            {
                var policy = new CorsPolicy();
                policy.Headers.Add("*");
                policy.Methods.Add("*");
                policy.Origins.Add("*");
                policy.SupportsCredentials = true;
                config.AddPolicy("policy", policy);
            });


            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    ValidAudience    = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
예제 #33
0
        public CorsPolicyAttribute()
        {
            // Create a CORS policy.
            _policy = new CorsPolicy();

            #region Headers
            var headers = ConfigurationManager.AppSettings[keyCorsHeaders];
            if (headers == "*")
            {
                _policy.AllowAnyHeader = true;
            }
            else
            {
                headers.Split(';').ToList().ForEach(i => _policy.Headers.Add(i));
            }
            #endregion

            #region Methods
            var methods = ConfigurationManager.AppSettings[keyCorsMethods];
            if (methods == "*")
            {
                _policy.AllowAnyMethod = true;
            }
            else
            {
                methods.Split(';').ToList().ForEach(i => _policy.Methods.Add(i));
            }
            #endregion

            #region Origins
            var origins = ConfigurationManager.AppSettings[keyCorsOrigins];
            if (origins == "*")
            {
                _policy.AllowAnyOrigin = true;
            }
            else
            {
                origins.Split(';').ToList().ForEach(i => _policy.Methods.Add(i));
            }
            #endregion
        }
예제 #34
0
        public async Task PreFlight_MatchesPolicy_SetsResponseHeaders()
        {
            // Arrange
            var policy = new CorsPolicy();

            policy.Origins.Add("http://localhost:5001");
            policy.Methods.Add("PUT");
            policy.Headers.Add("Header1");
            policy.ExposedHeaders.Add("AllowedHeader");

            using (var server = TestServer.Create(app =>
            {
                app.UseCors("customPolicy");
                app.Run(async context =>
                {
                    await context.Response.WriteAsync("Cross origin response");
                });
            },
                                                  services =>
            {
                services.AddCors();
                services.ConfigureCors(options =>
                {
                    options.AddPolicy("customPolicy", policy);
                });
            }))
            {
                // Act
                // Preflight request.
                var response = await server.CreateRequest("/")
                               .AddHeader(CorsConstants.Origin, "http://localhost:5001")
                               .AddHeader(CorsConstants.AccessControlRequestMethod, "PUT")
                               .SendAsync(CorsConstants.PreflightHttpMethod);

                // Assert
                response.EnsureSuccessStatusCode();
                Assert.Equal(2, response.Headers.Count());
                Assert.Equal("http://localhost:5001", response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault());
                Assert.Equal("PUT", response.Headers.GetValues(CorsConstants.AccessControlAllowMethods).FirstOrDefault());
            }
        }
예제 #35
0
        private static void ConfigureCors(IAppBuilder app)
        {
            CorsPolicy policy = new CorsPolicy
            {
                AllowAnyHeader      = true,
                AllowAnyMethod      = true,
                AllowAnyOrigin      = false,
                SupportsCredentials = true
            };

            policy.Origins.Add("http://teaminternational.admin:3000");
            policy.Origins.Add("http://company.admin:3000");

            app.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(policy)
                }
            });
        }
예제 #36
0
    public void EvaluatePolicy_PreflightRequest_WithCredentials_ReflectsHeaders()
    {
        // Arrange
        var corsService = GetCorsService();
        var httpContext = GetHttpContext(method: "OPTIONS", origin: "http://example.com", accessControlRequestMethod: "PUT");
        var policy      = new CorsPolicy();

        policy.Origins.Add("http://example.com");
        policy.Methods.Add("*");
        policy.Headers.Add("*");
        policy.SupportsCredentials = true;

        // Act
        var result = corsService.EvaluatePolicy(httpContext, policy);

        // Assert
        Assert.NotNull(result);
        Assert.Equal(new[] { "PUT" }, result.AllowedMethods);
        Assert.Empty(result.AllowedHeaders);
        Assert.True(result.SupportsCredentials);
    }
예제 #37
0
        public void EvaluatePolicy_PreflightRequest_PreflightMaxAge_PreflightMaxAgeSet()
        {
            CorsEngine         corsEngine     = new CorsEngine();
            CorsRequestContext requestContext = new CorsRequestContext
            {
                HttpMethod = "OPTIONS",
                AccessControlRequestMethod = "PUT",
                Origin = "foo",
            };
            CorsPolicy policy = new CorsPolicy
            {
                AllowAnyOrigin  = true,
                AllowAnyMethod  = true,
                PreflightMaxAge = 10
            };

            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);

            Assert.True(requestContext.IsPreflight);
            Assert.Equal(10, result.PreflightMaxAge);
        }
예제 #38
0
    public void EvaluatePolicy_PreflightRequest_IsOriginAllowedReturnsTrue_ReturnsOrigin()
    {
        // Arrange
        var corsService    = GetCorsService();
        var requestContext = GetHttpContext(
            method: "OPTIONS",
            origin: "http://example.com",
            accessControlRequestMethod: "PUT");
        var policy = new CorsPolicy
        {
            IsOriginAllowed = origin => true
        };

        policy.Methods.Add("*");

        // Act
        var result = corsService.EvaluatePolicy(requestContext, policy);

        // Assert
        Assert.Equal("http://example.com", result.AllowedOrigin);
    }
예제 #39
0
        public void EvaluatePolicy_PreflightRequest_NoHeadersRequested_AllowedAllHeaders_ReturnsEmptyHeaders()
        {
            CorsEngine         corsEngine     = new CorsEngine();
            CorsRequestContext requestContext = new CorsRequestContext
            {
                HttpMethod = "OPTIONS",
                AccessControlRequestMethod = "PUT",
                Origin = "foo",
            };
            CorsPolicy policy = new CorsPolicy
            {
                AllowAnyOrigin = true,
                AllowAnyMethod = true,
                AllowAnyHeader = true
            };

            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);

            Assert.True(requestContext.IsPreflight);
            Assert.Empty(result.AllowedHeaders);
        }
예제 #40
0
		// This method gets called by the runtime. Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services) {
			services.AddSingleton<ConnectionStringConfig>(new ConnectionStringConfig { ConnectionString = Configuration.GetConnectionString("DefaultConnection") });
			// Add framework services.
			services.AddApplicationInsightsTelemetry(Configuration);

			services.AddDbContext<MobileSecondHandContext>(options =>
				options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("MobileSecondHand")));

			services.AddMvc().AddJsonOptions(o =>
			{
				o.SerializerSettings.ContractResolver = new DefaultContractResolver();
			});

			services.AddAuthorization(auth => {
				auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
					.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
					.RequireAuthenticatedUser().Build());
			});
			DbServicesBootstrapper.RegisterServices(services);
			ApiServicesBootstrapper.RegisterServices(services);
			CommonServicesBootstrapper.RegisterServices(services);

			var policy = new CorsPolicy();
			policy.Headers.Add("*");
			policy.Methods.Add("*");
			policy.Origins.Add("*");

			services.AddCors(config => {
				config.AddPolicy("myPolicy", policy);
			});

			//services.AddSingleton<IAssemblyLocator, HubCouldNotBeResolvedWorkaround>();
			services.AddSignalR();


			//// Add application services.
			//services.AddTransient<IEmailSender, AuthMessageSender>();
			//         services.AddTransient<ISmsSender, AuthMessageSender>();
		}
예제 #41
0
        public void ToString_ReturnsThePropertyValues()
        {
            // Arrange
            var corsPolicy = new CorsPolicy
            {
                PreflightMaxAge = TimeSpan.FromSeconds(12),
                SupportsCredentials = true
            };
            corsPolicy.Headers.Add("foo");
            corsPolicy.Headers.Add("bar");
            corsPolicy.Origins.Add("http://example.com");
            corsPolicy.Origins.Add("http://example.org");
            corsPolicy.Methods.Add("GET");

            // Act
            var policyString = corsPolicy.ToString();

            // Assert
            Assert.Equal(
                @"AllowAnyHeader: False, AllowAnyMethod: False, AllowAnyOrigin: False, PreflightMaxAge: 12,"+
                " SupportsCredentials: True, Origins: {http://example.com,http://example.org}, Methods: {GET},"+
                " Headers: {foo,bar}, ExposedHeaders: {}",
                policyString);
        }
예제 #42
0
        public void EvaluatePolicy_DoesNotSupportCredentials_AllowCredentialsReturnsFalse()
        {
            // Arrange
            var corsService = new CorsService(new TestCorsOptions());
            var requestContext = GetHttpContext(origin: "http://example.com");
            var policy = new CorsPolicy
            {
                SupportsCredentials = false
            };
            policy.Origins.Add(CorsConstants.AnyOrigin);

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.False(result.SupportsCredentials);
        }
예제 #43
0
        public void EvaluatePolicy_EmptyOriginsPolicy_ReturnsInvalidResult()
        {
            // Arrange
            var corsService = new CorsService(new TestCorsOptions());
            var requestContext = GetHttpContext(origin: "http://example.com");
            var policy = new CorsPolicy();

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Null(result.AllowedOrigin);
            Assert.False(result.VaryByOrigin);
        }
예제 #44
0
        public void EvaluatePolicy_PreflightRequest_MethodAllowed_ReturnsAllowMethods()
        {
            // Arrange
            var corsService = new CorsService(new TestCorsOptions());
            var requestContext = GetHttpContext(method: "OPTIONS", origin: "http://example.com", accessControlRequestMethod: "PUT");
            var policy = new CorsPolicy();
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.Methods.Add("PUT");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.NotNull(result);
            Assert.Contains("PUT", result.AllowedMethods);
        }
예제 #45
0
        public void EvaluatePolicy_PreflightRequest_NoHeadersRequested_AllowedAllHeaders_ReturnsEmptyHeaders()
        {
            // Arrange
            var corsService = new CorsService(new TestCorsOptions());
            var requestContext = GetHttpContext(method: "OPTIONS", origin: "http://example.com", accessControlRequestMethod: "PUT");
            var policy = new CorsPolicy();
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.Methods.Add("*");
            policy.Headers.Add("*");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Empty(result.AllowedHeaders);
        }
예제 #46
0
        public void EaluatePolicy_DoesCaseSensitiveComparison()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());

            var policy = new CorsPolicy();
            policy.Methods.Add("POST");
            var httpContext = GetHttpContext(origin: null, accessControlRequestMethod: "post");

            // Act
            var result = corsService.EvaluatePolicy(httpContext, policy);

            // Assert
            Assert.Empty(result.AllowedHeaders);
            Assert.Empty(result.AllowedMethods);
            Assert.Empty(result.AllowedExposedHeaders);
            Assert.Null(result.AllowedOrigin);
        }
예제 #47
0
        public void Constructor_WithPolicy_AddsTheGivenPolicy()
        {
            // Arrange
            var policy = new CorsPolicy();
            policy.Origins.Add("http://existing.com");
            policy.Headers.Add("Existing");
            policy.Methods.Add("GET");
            policy.ExposedHeaders.Add("ExistingExposed");
            policy.SupportsCredentials = true;
            policy.PreflightMaxAge = TimeSpan.FromSeconds(12);

            // Act
            var builder = new CorsPolicyBuilder(policy);

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

            Assert.False(corsPolicy.AllowAnyHeader);
            Assert.False(corsPolicy.AllowAnyMethod);
            Assert.False(corsPolicy.AllowAnyOrigin);
            Assert.True(corsPolicy.SupportsCredentials);
            Assert.Equal(policy.Headers, corsPolicy.Headers);
            Assert.Equal(policy.Methods, corsPolicy.Methods);
            Assert.Equal(policy.Origins, corsPolicy.Origins);
            Assert.Equal(policy.ExposedHeaders, corsPolicy.ExposedHeaders);
            Assert.Equal(TimeSpan.FromSeconds(12), corsPolicy.PreflightMaxAge);
        }
예제 #48
0
        public void EvaluatePolicy_OneExposedHeaders_HeadersAllowed()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(origin: "http://example.com");
            var policy = new CorsPolicy();
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.ExposedHeaders.Add("foo");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Equal(1, result.AllowedExposedHeaders.Count);
            Assert.Contains("foo", result.AllowedExposedHeaders);
        }
예제 #49
0
        public void EvaluatePolicy_AllowAnyOrigin_SupportsCredentials_AddsSpecificOrigin()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(origin: "http://example.com");
            var policy = new CorsPolicy
            {
                SupportsCredentials = true
            };
            policy.Origins.Add(CorsConstants.AnyOrigin);

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Equal("http://example.com", result.AllowedOrigin);
            Assert.True(result.VaryByOrigin);
        }
예제 #50
0
        public void EvaluatePolicy_NoExposedHeaders_NoAllowExposedHeaders()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(origin: "http://example.com");
            var policy = new CorsPolicy();
            policy.Origins.Add(CorsConstants.AnyOrigin);

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Empty(result.AllowedExposedHeaders);
        }
예제 #51
0
        public void EvaluatePolicy_NoMatchingOrigin_ReturnsInvalidResult()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(origin: "http://example.com");
            var policy = new CorsPolicy();
            policy.Origins.Add("bar");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Null(result.AllowedOrigin);
            Assert.False(result.VaryByOrigin);
        }
예제 #52
0
        public void TryValidateOrigin_DoesCaseSensitiveComparison()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());

            var policy = new CorsPolicy();
            policy.Origins.Add("http://Example.com");
            var httpContext = GetHttpContext(origin: "http://example.com");

            // Act
            var result = corsService.EvaluatePolicy(httpContext, policy);

            // Assert
            Assert.Empty(result.AllowedHeaders);
            Assert.Empty(result.AllowedMethods);
            Assert.Empty(result.AllowedExposedHeaders);
            Assert.Null(result.AllowedOrigin);
        }
예제 #53
0
        public void EvaluatePolicy_SupportsCredentials_AllowCredentialsReturnsTrue()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(origin: "http://example.com");
            var policy = new CorsPolicy
            {
                SupportsCredentials = true
            };
            policy.Origins.Add(CorsConstants.AnyOrigin);

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.True(result.SupportsCredentials);
        }
예제 #54
0
        public void EvaluatePolicy_PreflightRequest_SupportsCredentials_AllowCredentialsReturnsTrue()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(method: "OPTIONS", origin: "http://example.com", accessControlRequestMethod: "PUT");
            var policy = new CorsPolicy
            {
                SupportsCredentials = true
            };
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.Methods.Add("*");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.True(result.SupportsCredentials);
        }
예제 #55
0
        public void EvaluatePolicy_PreflightRequest_PreflightMaxAge_PreflightMaxAgeSet()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(method: "OPTIONS", origin: "http://example.com", accessControlRequestMethod: "PUT");
            var policy = new CorsPolicy
            {
                PreflightMaxAge = TimeSpan.FromSeconds(10)
            };
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.Methods.Add("*");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Equal(TimeSpan.FromSeconds(10), result.PreflightMaxAge);
        }
예제 #56
0
        public void EvaluatePolicy_AllowAnyOrigin_DoesNotSupportCredentials_EmitsWildcardForOrigin()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(origin: "http://example.com");

            var policy = new CorsPolicy
            {
                SupportsCredentials = false
            };

            policy.Origins.Add(CorsConstants.AnyOrigin);

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Equal("*", result.AllowedOrigin);
        }
예제 #57
0
        public void EvaluatePolicy_PreflightRequest_HeadersRequested_NotAllHeaderMatches_ReturnsInvalidResult()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(
                method: "OPTIONS",
                origin: "http://example.com",
                accessControlRequestMethod: "PUT",
                accessControlRequestHeaders: new[] { "match", "noMatch" });
            var policy = new CorsPolicy();
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.Methods.Add("*");
            policy.Headers.Add("match");
            policy.Headers.Add("foo");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Empty(result.AllowedHeaders);
            Assert.Empty(result.AllowedMethods);
            Assert.Empty(result.AllowedExposedHeaders);
            Assert.Null(result.AllowedOrigin);
        }
예제 #58
0
        public void EvaluatePolicy_PreflightRequest_HeadersRequested_AllowSomeHeaders_ReturnsSubsetOfListedHeaders()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(
                method: "OPTIONS",
                origin: "http://example.com",
                accessControlRequestMethod: "PUT",
                accessControlRequestHeaders: new[] { "Content-Type" });
            var policy = new CorsPolicy();
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.Methods.Add("*");
            policy.Headers.Add("foo");
            policy.Headers.Add("bar");
            policy.Headers.Add("Content-Type");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Equal(1, result.AllowedHeaders.Count);
            Assert.Contains("Content-Type", result.AllowedHeaders);
        }
예제 #59
0
        public void EvaluatePolicy_PreflightRequest_NoPreflightMaxAge_NoPreflightMaxAgeSet()
        {
            // Arrange
            var corsService = new CorsService(new TestCorsOptions());
            var requestContext = GetHttpContext(method: "OPTIONS", origin: "http://example.com", accessControlRequestMethod: "PUT");
            var policy = new CorsPolicy
            {
                PreflightMaxAge = null
            };
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.Methods.Add("*");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Null(result.PreflightMaxAge);
        }
예제 #60
0
        public void EvaluatePolicy_PreflightRequest_OriginAllowed_ReturnsOrigin()
        {
            // Arrange
            var corsService = new CorsService(Mock.Of<IOptions<CorsOptions>>());
            var requestContext = GetHttpContext(method: "OPTIONS", origin: "http://example.com", accessControlRequestMethod: "PUT");
            var policy = new CorsPolicy();
            policy.Origins.Add(CorsConstants.AnyOrigin);
            policy.Origins.Add("http://example.com");
            policy.Methods.Add("*");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            // Assert
            Assert.Equal("http://example.com", result.AllowedOrigin);
        }