public void IsPreflight_ReturnsFalse(string httpMethod, string requestedMethod, string origin) { CorsRequestContext requestContext = new CorsRequestContext() { HttpMethod = httpMethod, AccessControlRequestMethod = requestedMethod, Origin = origin }; Assert.False(requestContext.IsPreflight); }
public void Default_Constructor() { CorsRequestContext requestContext = new CorsRequestContext(); Assert.Null(requestContext.AccessControlRequestMethod); Assert.Null(requestContext.Host); Assert.Null(requestContext.HttpMethod); Assert.Null(requestContext.Origin); Assert.Null(requestContext.RequestUri); Assert.NotNull(requestContext.AccessControlRequestHeaders); Assert.False(requestContext.IsPreflight); }
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); }
public void EvaluatePolicy_NoOrigin_ReturnsInvalidResult() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { Origin = null, HttpMethod = "GET" }; CorsResult result = corsEngine.EvaluatePolicy(requestContext, new CorsPolicy()); Assert.False(result.IsValid); Assert.Contains("The request does not contain the Origin header.", result.ErrorMessages); }
public void ToString_ReturnsThePropertyValues() { CorsRequestContext requestContext = new CorsRequestContext { Host = "http://example.com", HttpMethod = "OPTIONS", AccessControlRequestMethod = "DELETE", Origin = "http://localhost", RequestUri = new Uri("http://example.com") }; requestContext.AccessControlRequestHeaders.Add("foo"); requestContext.AccessControlRequestHeaders.Add("bar"); Assert.Equal(@"Origin: http://localhost, HttpMethod: OPTIONS, IsPreflight: True, Host: http://example.com, AccessControlRequestMethod: DELETE, RequestUri: http://example.com/, AccessControlRequestHeaders: {foo,bar}", requestContext.ToString()); }
public void EvaluatePolicy_AllowAnyOrigin_DoesNotSupportCredentials_EmitsWildcardForOrigin() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { Origin = "foo" }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true, SupportsCredentials = false }; CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.Equal("*", result.AllowedOrigin); }
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); }
public void EvaluatePolicy_Trace_ContainsHttpRequest() { // Arrange HttpRequestMessage httpRequest = new HttpRequestMessage( HttpMethod.Options, "http://example.com/test" ); httpRequest.Headers.Add("Origin", "foo"); CorsRequestContext corsRequestContext = httpRequest.GetCorsRequestContext(); Mock <ITraceWriter> traceWriterMock = new Mock <ITraceWriter>(); traceWriterMock .Setup( t => t.Trace( httpRequest, It.IsAny <string>(), It.IsAny <TraceLevel>(), It.IsAny <Action <TraceRecord> >() ) ) .Verifiable(); Mock <ICorsEngine> corsEngineMock = new Mock <ICorsEngine>(); corsEngineMock .Setup(engine => engine.EvaluatePolicy(corsRequestContext, It.IsAny <CorsPolicy>())) .Returns(new CorsResult()); CorsEngineTracer tracer = new CorsEngineTracer( corsEngineMock.Object, traceWriterMock.Object ); // Act tracer.EvaluatePolicy(corsRequestContext, new CorsPolicy()); // Assert traceWriterMock.Verify(); }
private Task <HttpResponseMessage> HandleCorsRequest( HttpRequestMessage request, CancellationToken cancellationToken, CorsRequestContext corsRequestContext) { if (corsRequestContext.IsPreflight) { return(HandleCorsPreflightRequest(corsRequestContext)); } return(base.Handle(request, cancellationToken) .ContinueWith(responseTask => { var response = responseTask.Result; WriteCorsHeaders(response, corsRequestContext); return response; })); }
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); }
private static CorsRequestContext GetCorsRequestContext(IOwinContext context) { string origin = context.Request.Headers.Get(CorsConstants.Origin); if (String.IsNullOrEmpty(origin)) { //尝试从 Http Referer中获取 string refer = context.Request.Headers.Get(CorsConstants.Referer); if (!string.IsNullOrEmpty(refer)) { origin = CorsConstants.GetUriAddress(refer); } } if (String.IsNullOrEmpty(origin)) { return(null); } var requestContext = new CorsRequestContext { RequestUri = context.Request.Uri, HttpMethod = context.Request.Method, Host = context.Request.Host.Value, Origin = origin, AccessControlRequestMethod = context.Request.Headers.Get(CorsConstants.AccessControlRequestMethod) }; IList <string> headerValues = context.Request.Headers.GetCommaSeparatedValues(CorsConstants.AccessControlRequestHeaders); if (headerValues != null) { foreach (var header in headerValues) { requestContext.AccessControlRequestHeaders.Add(header); } } return(requestContext); }
/// <summary> /// Gets the <see cref="CorsRequestContext"/> for a given request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/>.</param> /// <returns>The <see cref="CorsRequestContext"/>.</returns> /// <exception cref="System.ArgumentNullException">request</exception> public static CorsRequestContext GetCorsRequestContext(this HttpRequestMessage request) { if (request == null) { throw new ArgumentNullException("request"); } object corsRequestContext; if (!request.Properties.TryGetValue(CorsRequestContextKey, out corsRequestContext)) { if (!request.Headers.Contains(CorsConstants.Origin)) { return(null); } CorsRequestContext requestContext = new CorsRequestContext { RequestUri = request.RequestUri, HttpMethod = request.Method.Method, Host = request.Headers.Host, Origin = request.GetHeader(CorsConstants.Origin), AccessControlRequestMethod = request.GetHeader(CorsConstants.AccessControlRequestMethod) }; string allowAccessRequestHeaders = request.GetHeader(CorsConstants.AccessControlRequestHeaders); if (allowAccessRequestHeaders != null) { IEnumerable <string> headerValues = allowAccessRequestHeaders.Split(',').Select(x => x.Trim()); foreach (string header in headerValues) { requestContext.AccessControlRequestHeaders.Add(header); } } request.Properties.Add(CorsRequestContextKey, requestContext); corsRequestContext = requestContext; } return((CorsRequestContext)corsRequestContext); }
public CorsResult EvaluatePolicy(CorsRequestContext context, CorsPolicy policy) { var origin = context.Origin; var domain = string.Empty; // 匹配域名 foreach (var ori in policy.Origins) { if (RegexHelper.Match(origin, ori)) { domain = origin; break; } } WildcardCorsResult result = new WildcardCorsResult(policy, context); result.AllowedOrigin = domain; return(result); }
public void EvaluatePolicy_PreflightRequest_MethodAllowed_ReturnsAllowMethods() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { HttpMethod = "OPTIONS", AccessControlRequestMethod = "PUT", Origin = "foo" }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true }; policy.Methods.Add("PUT"); CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(requestContext.IsPreflight); Assert.NotNull(result); Assert.Contains("PUT", result.AllowedMethods); }
public void EvaluatePolicy_ManyExposedHeaders_HeadersAllowed() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { Origin = "foo" }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true }; policy.ExposedHeaders.Add("foo"); policy.ExposedHeaders.Add("bar"); policy.ExposedHeaders.Add("baz"); CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.Equal(3, result.AllowedExposedHeaders.Count()); Assert.Contains("foo", result.AllowedExposedHeaders); Assert.Contains("bar", result.AllowedExposedHeaders); Assert.Contains("baz", result.AllowedExposedHeaders); }
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); }
public void EvaluatePolicy_PreflightRequest_SupportsCredentials_AllowCredentialsReturnsTrue() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { HttpMethod = "OPTIONS", AccessControlRequestMethod = "PUT", Origin = "foo", }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true, AllowAnyMethod = true, SupportsCredentials = true }; CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(requestContext.IsPreflight); Assert.True(result.SupportsCredentials); }
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); }
public void EvaluatePolicy_PreflightRequest_MethodNotAllowed_ReturnsInvalidResult() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { HttpMethod = "OPTIONS", AccessControlRequestMethod = "PUT", Origin = "foo" }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true }; policy.Methods.Add("GET"); CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(requestContext.IsPreflight); Assert.False(result.IsValid); Assert.Contains("The method 'PUT' is not allowed.", result.ErrorMessages); }
public CorsResult EvaluatePolicy(CorsRequestContext requestContext, CorsPolicy policy) { CorsResult corsResult = null; object request; requestContext.Properties.TryGetValue(typeof(HttpRequestMessage).FullName, out request); _traceWriter.TraceBeginEnd( request as HttpRequestMessage, TraceCategories.CorsCategory, TraceLevel.Info, _innerCorsEngine.GetType().Name, MethodName, beginTrace: null, execute: () => { corsResult = _innerCorsEngine.EvaluatePolicy(requestContext, policy); }, endTrace: (tr) => { if (corsResult != null) { tr.Message = String.Format( CultureInfo.CurrentCulture, SRResources.TraceEndCorsResultReturned, corsResult ); } else { tr.Message = SRResources.TraceEndNoCorsResultReturned; } }, errorTrace: null ); return(corsResult); }
public void EvaluatePolicy_PreflightRequest_ListedMethod_ReturnsSubsetOfListedMethods() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { HttpMethod = "OPTIONS", AccessControlRequestMethod = "PUT", Origin = "foo" }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true }; policy.Methods.Add("PUT"); policy.Methods.Add("DELETE"); CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(requestContext.IsPreflight); Assert.Equal(1, result.AllowedMethods.Count()); Assert.Contains("PUT", result.AllowedMethods); }
public async Task <CorsPolicy> GetCorsPolicyAsync( HttpRequestMessage request, CancellationToken cancellationToken) { CorsRequestContext corsRequestContext = request.GetCorsRequestContext(); string originRequested = corsRequestContext.Origin; if (await IsOriginFromAPaidCustomer(originRequested)) { // Grant CORS request CorsPolicy policy = new CorsPolicy { AllowAnyHeader = true, AllowAnyMethod = true, }; policy.Origins.Add(originRequested); return(policy); } else { // Reject CORS request return(null); } }
/// <summary> /// Evaluates and applies the CORS policy. Responses will be generated for preflight requests. /// Requests that are permitted by the CORS policy will be passed onto the next middleware. /// </summary> /// <param name="environment"></param> /// <returns></returns> public async Task Invoke(IDictionary <string, object> environment) { IOwinContext context = new OwinContext(environment); CorsRequestContext corsRequestContext = GetCorsRequestContext(context); CorsPolicy policy = await _corsPolicyProvider.GetCorsPolicyAsync(context.Request); if (policy != null && corsRequestContext != null) { if (corsRequestContext.IsPreflight) { await HandleCorsPreflightRequestAsync(context, policy, corsRequestContext); } else { await HandleCorsRequestAsync(context, policy, corsRequestContext); } } else { await _next(environment); } }
private CorsRequestContext GetCorsRequestContext( HttpRequestMessage request) { var origin = request.Headers.GetOrigin(); if (origin.IsNullOrEmpty()) { return(null); } var context = new CorsRequestContext { RequestUri = request.RequestUri, HttpMethod = request.Method.ToString(), Host = request.Headers.Host, Origin = origin, AccessControlRequestMethod = request.Headers.GetAccessControlRequestMethod(), }; context.SetAccessControlRequestHeaders( request.Headers.GetAccessControlRequestHeaders()); return(context); }
private async Task <HttpResponseMessage> HandleRequest(bool preflight, CorsRequestContext requestContext, GraphiteCorsPolicy corsPolicy) { if (preflight && !_configuration.SupportedHttpMethods.Contains( requestContext.AccessControlRequestMethod)) { return(await FailRequest(corsPolicy, true)); } var result = _corsEngine.EvaluatePolicy(requestContext, corsPolicy); if (result == null || !result.IsValid) { return(await FailRequest(corsPolicy, preflight, result?.ErrorMessages.Join(" "))); } var response = !preflight || corsPolicy.AllowOptionRequestsToPassThrough ? await BehaviorChain.InvokeNext() : _requestMessage.CreateResponse(); response.WriteCorsHeaders(result); return(response); }
private void ProcessCors(OAuthValidateTokenRequestContext context) { var accessControlRequestMethodHeaders = context.Request.Headers.GetCommaSeparatedValues(CorsConstants.AccessControlRequestMethod); var originHeaders = context.Request.Headers.GetCommaSeparatedValues(CorsConstants.Origin); var accessControlRequestHeaders = context.Request.Headers.GetCommaSeparatedValues(CorsConstants.AccessControlRequestMethod); var corsRequest = new CorsRequestContext { Host = context.Request.Host.Value, HttpMethod = context.Request.Method, Origin = originHeaders?.FirstOrDefault(), RequestUri = context.Request.Uri, AccessControlRequestMethod = accessControlRequestMethodHeaders?.FirstOrDefault() }; if (accessControlRequestHeaders != null) { foreach (var header in context.Request.Headers.GetCommaSeparatedValues(CorsConstants.AccessControlRequestMethod)) { corsRequest.AccessControlRequestHeaders.Add(header); } } var engine = new CorsEngine(); if (corsRequest.IsPreflight) { try { // Make sure Access-Control-Request-Method is valid. var test = new HttpMethod(corsRequest.AccessControlRequestMethod); } catch (ArgumentException) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.SetError("Access Control Request Method Cannot Be Null Or Empty"); //context.RequestCompleted(); return; } catch (FormatException) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.SetError("Invalid Access Control Request Method"); //context.RequestCompleted(); return; } var result = engine.EvaluatePolicy(corsRequest, _options.CorsPolicy); if (!result.IsValid) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.SetError(string.Join(" | ", result.ErrorMessages)); //context.RequestCompleted(); return; } WriteCorsHeaders(result, context); } else { var result = engine.EvaluatePolicy(corsRequest, _options.CorsPolicy); if (result.IsValid) { WriteCorsHeaders(result, context); } } }
public virtual ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request) { if (request == null) { throw new ArgumentNullException("request"); } CorsRequestContext corsRequestContext = request.GetCorsRequestContext(); HttpActionDescriptor actionDescriptor = null; if (corsRequestContext.IsPreflight) { HttpRequestMessage targetRequest = new HttpRequestMessage(new HttpMethod(corsRequestContext.AccessControlRequestMethod), request.RequestUri); request.RegisterForDispose(targetRequest); try { foreach (var property in request.Properties) { // The RouteData and HttpContext from the preflight request properties contain information // relevant to the preflight request and not the actual request, therefore we need to exclude them. if (property.Key != HttpPropertyKeys.HttpRouteDataKey && property.Key != HttpContextBaseKey) { targetRequest.Properties.Add(property.Key, property.Value); } } HttpConfiguration config = request.GetConfiguration(); if (config == null) { throw new InvalidOperationException(SRResources.NoConfiguration); } IHttpRouteData routeData = config.Routes.GetRouteData(request); if (routeData == null) { // No route data found for selecting action with EnableCorsAttribute, thus no ICorsPolicyProvider is returned // and let the CorsMessageHandler flow the request to the normal Web API pipeline. return(null); } actionDescriptor = SelectAction(targetRequest, routeData, config); } catch { if (DefaultPolicyProvider != null) { return(DefaultPolicyProvider); } throw; } } else { actionDescriptor = request.GetActionDescriptor(); } return(GetCorsPolicyProvider(actionDescriptor)); }
/// <summary> /// Handles the preflight request specified by CORS. /// </summary> /// <param name="request">The request.</param> /// <param name="corsRequestContext">The cors request context.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The <see cref="Task{HttpResponseMessage}"/></returns> /// <exception cref="System.ArgumentNullException"> /// request /// or /// corsRequestContext /// </exception> public virtual async Task <HttpResponseMessage> HandleCorsPreflightRequestAsync(HttpRequestMessage request, CorsRequestContext corsRequestContext, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (request == null) { throw new ArgumentNullException("request"); } if (corsRequestContext == null) { throw new ArgumentNullException("corsRequestContext"); } CorsPolicy corsPolicy = await GetCorsPolicyAsync(request); if (corsPolicy != null) { HttpResponseMessage response = null; CorsResult result; if (TryEvaluateCorsPolicy(corsRequestContext, corsPolicy, out result)) { response = request.CreateResponse(HttpStatusCode.OK); response.WriteCorsHeaders(result); } else { response = result != null? request.CreateErrorResponse(HttpStatusCode.BadRequest, String.Join(" | ", result.ErrorMessages)) : request.CreateResponse(HttpStatusCode.BadRequest); } return(response); } else { return(await base.SendAsync(request, cancellationToken)); } }
public void EvaluatePolicy_SupportsCredentials_AllowCredentialsReturnsTrue() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { Origin = "foo" }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true, SupportsCredentials = true }; CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(result.SupportsCredentials); }
/// <summary> /// Handles the actual CORS request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/>.</param> /// <param name="corsRequestContext">The <see cref="CorsRequestContext"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> /// <returns>The <see cref="Task{HttpResponseMessage}"/>.</returns> /// <exception cref="System.ArgumentNullException"> /// request /// or /// corsRequestContext /// </exception> public virtual async Task <HttpResponseMessage> HandleCorsRequestAsync(HttpRequestMessage request, CorsRequestContext corsRequestContext, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request"); } if (corsRequestContext == null) { throw new ArgumentNullException("corsRequestContext"); } HttpResponseMessage response = await base.SendAsync(request, cancellationToken); CorsPolicy corsPolicy = await GetCorsPolicyAsync(request, cancellationToken); if (corsPolicy != null) { CorsResult result; if (TryEvaluateCorsPolicy(corsRequestContext, corsPolicy, out result)) { if (response != null) { response.WriteCorsHeaders(result); } } } return(response); }
private Task HandleCorsPreflightRequestAsync(IOwinContext context, CorsPolicy policy, CorsRequestContext corsRequestContext) { CorsResult result; if (!String.IsNullOrEmpty(corsRequestContext.AccessControlRequestMethod) && TryEvaluateCorsPolicy(policy, corsRequestContext, out result)) { context.Response.StatusCode = 200; WriteCorsHeaders(context, result); } else { // We couldn't evaluate the cors policy so it's a bad request context.Response.StatusCode = 400; } return(Task.FromResult(0)); }
public void EvaluatePolicy_NoExposedHeaders_NoAllowExposedHeaders() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { Origin = "foo" }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true }; CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.Empty(result.AllowedExposedHeaders); }
public void EvaluatePolicy_PreflightRequest_HeadersRequested_NotAllHeaderMatches_ReturnsInvalidResult() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { HttpMethod = "OPTIONS", AccessControlRequestMethod = "PUT", Origin = "foo" }; requestContext.AccessControlRequestHeaders.Add("match"); requestContext.AccessControlRequestHeaders.Add("noMatch"); CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true, AllowAnyMethod = true }; policy.Headers.Add("match"); policy.Headers.Add("foo"); CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(requestContext.IsPreflight); Assert.False(result.IsValid); Assert.Contains("The collection of headers 'match,noMatch' is not allowed.", result.ErrorMessages); }
public WildcardCorsResult(CorsPolicy policy, CorsRequestContext context) { this.policy = policy; this.context = context; }
public void EvaluatePolicy_PreflightRequest_HeadersRequested_AllowSomeHeaders_ReturnsSubsetOfListedHeaders() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { HttpMethod = "OPTIONS", AccessControlRequestMethod = "PUT", Origin = "foo" }; requestContext.AccessControlRequestHeaders.Add("Content-Type"); CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true, AllowAnyMethod = true }; policy.Headers.Add("foo"); policy.Headers.Add("bar"); policy.Headers.Add("Content-Type"); CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(requestContext.IsPreflight); Assert.Equal(1, result.AllowedHeaders.Count); Assert.Contains("Content-Type", result.AllowedHeaders); }
private bool TryEvaluateCorsPolicy(CorsPolicy policy, CorsRequestContext corsRequestContext, out CorsResult result) { result = _corsEngine.EvaluatePolicy(corsRequestContext, policy); return(result != null && result.IsValid); }
public void EvaluatePolicy_AllowAnyOrigin_SupportsCredentials_AddsSpecificOrigin() { CorsEngine corsEngine = new CorsEngine(); CorsRequestContext requestContext = new CorsRequestContext { Origin = "foo" }; CorsPolicy policy = new CorsPolicy { AllowAnyOrigin = true, SupportsCredentials = true }; CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.Equal("foo", result.AllowedOrigin); }
/// <summary> /// Handles the preflight request specified by CORS. /// </summary> /// <param name="request">The request.</param> /// <param name="corsRequestContext">The cors request context.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The <see cref="Task{HttpResponseMessage}"/></returns> /// <exception cref="System.ArgumentNullException"> /// request /// or /// corsRequestContext /// </exception> public virtual async Task <HttpResponseMessage> HandleCorsPreflightRequestAsync(HttpRequestMessage request, CorsRequestContext corsRequestContext, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request"); } if (corsRequestContext == null) { throw new ArgumentNullException("corsRequestContext"); } try { // Make sure Access-Control-Request-Method is valid. new HttpMethod(corsRequestContext.AccessControlRequestMethod); } catch (ArgumentException) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, SRResources.AccessControlRequestMethodCannotBeNullOrEmpty)); } catch (FormatException) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, String.Format(CultureInfo.CurrentCulture, SRResources.InvalidAccessControlRequestMethod, corsRequestContext.AccessControlRequestMethod))); } CorsPolicy corsPolicy = await GetCorsPolicyAsync(request, cancellationToken); if (corsPolicy != null) { HttpResponseMessage response = null; CorsResult result; if (TryEvaluateCorsPolicy(corsRequestContext, corsPolicy, out result)) { response = request.CreateResponse(HttpStatusCode.OK); response.WriteCorsHeaders(result); } else { response = result != null? request.CreateErrorResponse(HttpStatusCode.BadRequest, String.Join(" | ", result.ErrorMessages)) : request.CreateResponse(HttpStatusCode.BadRequest); } return(response); } else { return(await base.SendAsync(request, cancellationToken)); } }