Ejemplo n.º 1
0
        private bool TryEvaluateCorsPolicy(CorsRequestContext requestContext, CorsPolicy corsPolicy, out CorsResult corsResult)
        {
            ICorsEngine engine = _httpConfiguration.GetCorsEngine();

            corsResult = engine.EvaluatePolicy(requestContext, corsPolicy);
            return(corsResult != null && corsResult.IsValid);
        }
Ejemplo n.º 2
0
        public CorsResult EvaluatePolicy(CorsRequestContext requestContext, CorsPolicy policy)
        {
            CorsResult corsResult = null;

            _traceWriter.TraceBeginEnd(
                null,
                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);
        }
Ejemplo n.º 3
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.Request.Headers.Contains(ApiKeyHeader))
            {
                base.OnActionExecuting(actionContext);
                return;
            }

            var apiKeyValue = actionContext.Request.Headers.GetValues(ApiKeyHeader).First();

            var key = _apiKeys.Find(k => k.Key.Equals(new Guid(apiKeyValue)));

            if (key == null)
            {
                actionContext.Response = CreateResponseMessage(HttpStatusCode.Forbidden, $"Unknown API Key {apiKeyValue}");
                throw new HttpResponseException(actionContext.Response);
            }

            if (!key.Origins.Any())
            {
                base.OnActionExecuting(actionContext);
                return;
            }

            var remoteHost  = GetRemoteHost(actionContext.Request);
            var corsContext = new CorsRequestContext
            {
                Host       = remoteHost,
                Origin     = remoteHost,
                RequestUri = actionContext.Request.RequestUri,
            };

            var policy = new CorsPolicy();

            key.Origins.ForEach(origin => policy.Origins.Add(origin));

            var result = _corsEngine.EvaluatePolicy(corsContext, policy);

            if (result.IsValid)
            {
                base.OnActionExecuting(actionContext);
                return;
            }

            actionContext.Response = CreateResponseMessage(HttpStatusCode.Forbidden, $"API Key {key.Key} is not allowed from origin {corsContext.Origin}");
            throw new HttpResponseException(actionContext.Response);
        }
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //根据当前请求创建CorsRequestContext
            CorsRequestContext context = request.CreateCorsRequestContext();

            //针对非预检请求:将请求传递给消息处理管道后续部分继续处理,并得到响应
            HttpResponseMessage response = null;

            if (!context.IsPreflight)
            {
                response = await base.SendAsync(request, cancellationToken);
            }

            //利用注册的CorsPolicyProviderFactory得到对应的CorsPolicyProvider
            //借助于CorsPolicyProvider得到表示CORS资源授权策略的CorsPolicy
            HttpConfiguration configuration = request.GetConfiguration();
            CorsPolicy        policy        = await configuration.GetCorsPolicyProviderFactory().GetCorsPolicyProvider(request).GetCorsPolicyAsync(request, cancellationToken);

            //获取注册的CorsEngine
            //利用CorsEngine对请求实施CORS资源授权检验,并得到表示检验结果的CorsResult对象
            ICorsEngine engine = configuration.GetCorsEngine();
            CorsResult  result = engine.EvaluatePolicy(context, policy);

            //针对预检请求
            //如果请求通过授权检验,返回一个状态为“200, OK”的响应并添加CORS报头
            //如果授权检验失败,返回一个状态为“400, Bad Request”的响应并指定授权失败原因
            if (context.IsPreflight)
            {
                if (result.IsValid)
                {
                    response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.AddCorsHeaders(result);
                }
                else
                {
                    response = request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join(" |", result.ErrorMessages.ToArray()));
                }
            }
            //针对非预检请求
            //CORS报头只有在通过授权检验情况下才会被添加到响应报头集合中
            else if (result.IsValid)
            {
                response.AddCorsHeaders(result);
            }
            return(response);
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
 private bool TryEvaluateCorsPolicy(CorsPolicy policy, CorsRequestContext corsRequestContext, out CorsResult result)
 {
     result = _corsEngine.EvaluatePolicy(corsRequestContext, policy);
     return(result != null && result.IsValid);
 }