From 2dbfb8839b83ca31fb2f996a4d80e09deb60d904 Mon Sep 17 00:00:00 2001 From: Michiel Post Date: Thu, 22 Dec 2016 00:49:50 +0100 Subject: [PATCH] Include VaryByOrigin when there are multiple Origins configured (#84) Fixes #97 * Added negative test and updated origin to valid origin url * Fixed tabs and spaces --- .../Infrastructure/CorsService.cs | 5 +++ .../CorsServiceTests.cs | 35 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/Microsoft.AspNetCore.Cors/Infrastructure/CorsService.cs b/src/Microsoft.AspNetCore.Cors/Infrastructure/CorsService.cs index bd978495fb..5060ddf205 100644 --- a/src/Microsoft.AspNetCore.Cors/Infrastructure/CorsService.cs +++ b/src/Microsoft.AspNetCore.Cors/Infrastructure/CorsService.cs @@ -271,6 +271,11 @@ namespace Microsoft.AspNetCore.Cors.Infrastructure else if (policy.IsOriginAllowed(origin)) { result.AllowedOrigin = origin; + + if(policy.Origins.Count > 1) + { + result.VaryByOrigin = true; + } } } diff --git a/test/Microsoft.AspNetCore.Cors.Test/CorsServiceTests.cs b/test/Microsoft.AspNetCore.Cors.Test/CorsServiceTests.cs index 73b6e89653..40164da6d7 100644 --- a/test/Microsoft.AspNetCore.Cors.Test/CorsServiceTests.cs +++ b/test/Microsoft.AspNetCore.Cors.Test/CorsServiceTests.cs @@ -1080,6 +1080,41 @@ namespace Microsoft.AspNetCore.Cors.Infrastructure Assert.Equal("30", httpContext.Response.Headers["Access-Control-Max-Age"]); } + [Fact] + public void EvaluatePolicy_MultiOriginsPolicy_ReturnsVaryByOriginHeader() + { + // Arrange + var corsService = new CorsService(new TestCorsOptions()); + var requestContext = GetHttpContext(origin: "http://example.com"); + var policy = new CorsPolicy(); + policy.Origins.Add("http://example.com"); + policy.Origins.Add("http://example-two.com"); + + // Act + var result = corsService.EvaluatePolicy(requestContext, policy); + + // Assert + Assert.NotNull(result.AllowedOrigin); + Assert.True(result.VaryByOrigin); + } + + [Fact] + public void EvaluatePolicy_MultiOriginsPolicy_NoMatchingOrigin_ReturnsInvalidResult() + { + // Arrange + var corsService = new CorsService(new TestCorsOptions()); + var requestContext = GetHttpContext(origin: "http://example.com"); + var policy = new CorsPolicy(); + policy.Origins.Add("http://example-two.com"); + policy.Origins.Add("http://example-three.com"); + + // Act + var result = corsService.EvaluatePolicy(requestContext, policy); + + // Assert + Assert.Null(result.AllowedOrigin); + Assert.False(result.VaryByOrigin); + } private static HttpContext GetHttpContext(