// IMyScopedService is injected into Invoke public async Task Invoke(HttpContext httpContext) { var policy = CorsHelper.SetupCors().Build(); var origin = httpContext.Request.Headers[CorsConstants.Origin]; StringBuilder output = new StringBuilder(); output.AppendLine($"\n-----------\nCORS request at {DateTime.Now} from {httpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown IP"}"); output.AppendLine($"policy origins: {string.Join(",", policy.Origins)}, origin: {origin}, allowed: {policy.IsOriginAllowed(origin)}"); try { CorsResult result = _service.EvaluatePolicy(httpContext, policy); output.AppendLine(result.ToString()); output.AppendLine($"is origin allowed: {result.IsOriginAllowed}"); output.AppendLine($"headers before applying cors: {PrintHeaders(httpContext.Response)}"); _service.ApplyResult(result, httpContext.Response); output.AppendLine($"headers after applying cors: {PrintHeaders(httpContext.Response)}"); output.AppendLine($"is origin allowed: {result.IsOriginAllowed}"); } catch (Exception e) { output.AppendLine($"Caught {e.Message}: {e.StackTrace}"); } _logger.LogInformation(output.ToString()); await _next(httpContext); }
public void ToString_ReturnsThePropertyValues() { CorsResult corsResult = new CorsResult { SupportsCredentials = true, PreflightMaxAge = 20, AllowedOrigin = "*" }; corsResult.AllowedExposedHeaders.Add("foo"); corsResult.AllowedHeaders.Add("bar"); corsResult.AllowedHeaders.Add("baz"); corsResult.AllowedMethods.Add("GET"); corsResult.ErrorMessages.Add("error1"); corsResult.ErrorMessages.Add("error2"); Assert.Equal( @"IsValid: False, AllowCredentials: True, PreflightMaxAge: 20, AllowOrigin: *, AllowExposedHeaders: {foo}, AllowHeaders: {bar,baz}, AllowMethods: {GET}, ErrorMessages: {error1,error2}", corsResult.ToString() ); }
public void ToString_ReturnsThePropertyValues() { // Arrange var corsResult = new CorsResult { SupportsCredentials = true, PreflightMaxAge = TimeSpan.FromSeconds(30), AllowedOrigin = "*" }; corsResult.AllowedExposedHeaders.Add("foo"); corsResult.AllowedHeaders.Add("bar"); corsResult.AllowedHeaders.Add("baz"); corsResult.AllowedMethods.Add("GET"); // Act var result = corsResult.ToString(); // Assert Assert.Equal( @"AllowCredentials: True, PreflightMaxAge: 30, AllowOrigin: *," + " AllowExposedHeaders: {foo}, AllowHeaders: {bar,baz}, AllowMethods: {GET}", result); }
public void ToString_ReturnsThePropertyValues() { CorsResult corsResult = new CorsResult { SupportsCredentials = true, PreflightMaxAge = 20, AllowedOrigin = "*" }; corsResult.AllowedExposedHeaders.Add("foo"); corsResult.AllowedHeaders.Add("bar"); corsResult.AllowedHeaders.Add("baz"); corsResult.AllowedMethods.Add("GET"); corsResult.ErrorMessages.Add("error1"); corsResult.ErrorMessages.Add("error2"); Assert.Equal(@"IsValid: False, AllowCredentials: True, PreflightMaxAge: 20, AllowOrigin: *, AllowExposedHeaders: {foo}, AllowHeaders: {bar,baz}, AllowMethods: {GET}, ErrorMessages: {error1,error2}", corsResult.ToString()); }