public async Task Invoke(DownstreamContext context)
        {
            string token = context.HttpContext.Request.Headers["Token"].ToString();

            string path = context.HttpContext.Request.Path;

            if (path == _userApiAddress)
            {
                await _next.Invoke(context);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(token))
                {
                    SetPipelineError(context, new UnauthenticatedError("unauthorized, need login"));
                    return;
                }

                //调用UserAPI,校验权限

                HttpClientHelper httpClient = new HttpClientHelper();

                var result = httpClient.Get <ResultModel>(_userApiAddress + "?token=" + token);

                if (!result.Success)
                {
                    SetPipelineError(context, new UnauthenticatedError("unauthorized, need login"));
                    return;
                }
            }

            await _next.Invoke(context);
        }
Ejemplo n.º 2
0
        public async Task Invoke(DownstreamContext context)
        {
            if (context.HttpContext.Request.Method.ToUpper() != "OPTIONS" && IsAuthenticatedRoute(context.DownstreamReRoute))
            {
                Logger.LogInformation($"{context.HttpContext.Request.Path} is an authenticated route. {MiddlewareName} checking if client is authenticated");

                var result = await context.HttpContext.AuthenticateAsync(context.DownstreamReRoute.AuthenticationOptions.AuthenticationProviderKey);

                context.HttpContext.User = result.Principal;

                if (context.HttpContext.User.Identity.IsAuthenticated)
                {
                    Logger.LogInformation($"Client has been authenticated for {context.HttpContext.Request.Path}");
                    await _next.Invoke(context);
                }
                else
                {
                    var error = new UnauthenticatedError(
                        $"Request for authenticated route {context.HttpContext.Request.Path} by {context.HttpContext.User.Identity.Name} was unauthenticated");

                    Logger.LogWarning($"Client has NOT been authenticated for {context.HttpContext.Request.Path} and pipeline error set. {error}");

                    SetPipelineError(context, error);
                }
            }
            else
            {
                Logger.LogInformation($"No authentication needed for {context.HttpContext.Request.Path}");

                await _next.Invoke(context);
            }
        }
Ejemplo n.º 3
0
        public async Task Invoke(DownstreamContext context)
        {
            if (IsAuthenticatedRoute(context.DownstreamReRoute))
            {
                _logger.LogDebug($"{context.HttpContext.Request.Path} is an authenticated route. {MiddlewareName} checking if client is authenticated");

                var result = await context.HttpContext.AuthenticateAsync(context.DownstreamReRoute.AuthenticationOptions.AuthenticationProviderKey);

                context.HttpContext.User = result.Principal;

                if (context.HttpContext.User.Identity.IsAuthenticated)
                {
                    _logger.LogDebug($"Client has been authenticated for {context.HttpContext.Request.Path}");
                    await _next.Invoke(context);
                }
                else
                {
                    var error = new List <Error>
                    {
                        new UnauthenticatedError(
                            $"Request for authenticated route {context.HttpContext.Request.Path} by {context.HttpContext.User.Identity.Name} was unauthenticated")
                    };

                    _logger.LogError($"Client has NOT been authenticated for {context.HttpContext.Request.Path} and pipeline error set. {error.ToErrorString()}");

                    SetPipelineError(context, error);
                }
            }
            else
            {
                _logger.LogTrace($"No authentication needed for {context.HttpContext.Request.Path}");

                await _next.Invoke(context);
            }
        }
Ejemplo n.º 4
0
        public async Task Invoke(DownstreamContext context)
        {
            var options = context.DownstreamReRoute.RateLimitOptions;

            // check if rate limiting is enabled
            if (!context.DownstreamReRoute.EnableEndpointEndpointRateLimiting)
            {
                Logger.LogInformation($"EndpointRateLimiting is not enabled for {context.DownstreamReRoute.DownstreamPathTemplate.Value}");
                await _next.Invoke(context);

                return;
            }

            // compute identity from request
            var identity = SetIdentity(context.HttpContext, options);

            // check white list
            if (IsWhitelisted(identity, options))
            {
                Logger.LogInformation($"{context.DownstreamReRoute.DownstreamPathTemplate.Value} is white listed from rate limiting");
                await _next.Invoke(context);

                return;
            }

            var rule = options.RateLimitRule;

            if (rule.Limit > 0)
            {
                // increment counter
                var counter = _processor.ProcessRequest(identity, options);

                // check if limit is reached
                if (counter.TotalRequests > rule.Limit)
                {
                    //compute retry after value
                    var retryAfter = _processor.RetryAfterFrom(counter.Timestamp, rule);

                    // log blocked request
                    LogBlockedRequest(context.HttpContext, identity, counter, rule, context.DownstreamReRoute);

                    var retrystring = retryAfter.ToString(System.Globalization.CultureInfo.InvariantCulture);

                    // break execution
                    await ReturnQuotaExceededResponse(context.HttpContext, options, retrystring);

                    return;
                }
            }

            //set X-Rate-Limit headers for the longest period
            if (!options.DisableRateLimitHeaders)
            {
                var headers = _processor.GetRateLimitHeaders(context.HttpContext, identity, options);
                context.HttpContext.Response.OnStarting(SetRateLimitHeaders, state: headers);
            }

            await _next.Invoke(context);
        }
        public async Task Invoke(DownstreamContext context)
        {
            var clientId = "client_cjy"; //使用默认的客户端

            if (!context.IsError)
            {
                if (!_options.ClientRateLimit)
                {
                    Logger.LogInformation($"未启用客户端限流中间件");
                    await _next.Invoke(context);
                }
                else
                {
                    //非认证的渠道
                    if (!context.DownstreamReRoute.IsAuthenticated)
                    {
                        if (context.HttpContext.Request.Headers.Keys.Contains(_options.ClientKey))
                        {
                            clientId = context.HttpContext.Request.Headers[_options.ClientKey].First();
                        }
                    }
                    else
                    {//认证过的渠道,从Claim中提取
                        var clientClaim = context.HttpContext.User.Claims.FirstOrDefault(p => p.Type == _options.ClientKey);
                        if (!string.IsNullOrEmpty(clientClaim?.Value))
                        {
                            clientId = clientClaim?.Value;
                        }
                    }
                    //路由地址
                    var path = context.DownstreamReRoute.UpstreamPathTemplate.OriginalValue;
                    //1、校验路由是否有限流策略
                    //2、校验客户端是否被限流了
                    //3、校验客户端是否启动白名单
                    //4、校验是否触发限流及计数
                    if (await _clientRateLimitProcessor.CheckClientRateLimitResultAsync(clientId, path))
                    {
                        await _next.Invoke(context);
                    }
                    else
                    {
                        var error = new RateLimitOptionsError($"请求路由 {context.HttpContext.Request.Path}触发限流策略");
                        Logger.LogWarning($"路由地址 {context.HttpContext.Request.Path} 触发限流策略. {error}");
                        SetPipelineError(context, error);
                    }
                }
            }
            else
            {
                await _next.Invoke(context);
            }
        }
Ejemplo n.º 6
0
        public async Task Invoke(DownstreamContext context)
        {
            await _next.Invoke(context);

            if (context.IsError)
            {
                //  Logger.LogWarning($"{context.Errors.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{context.HttpContext.Request.Path}, request method: {context.HttpContext.Request.Method}");

                // SetErrorResponse(context.HttpContext, context.Errors);

                var errmsg     = context.Errors[0].Message;
                int httpstatus = _codeMapper.Map(context.Errors);
                var errResult  = new ErrorResult()
                {
                    errcode = httpstatus, errmsg = errmsg
                };
                var message = errResult.ToJson();
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                await context.HttpContext.Response.WriteAsync(message);

                return;
            }
            else if (context.DownstreamResponse == null)
            {//添加如果管道强制终止,不做任何处理,修复未将对象实例化错误
            }
            else
            {
                Logger.LogDebug("no pipeline errors, setting and returning completed response");
                await _responder.SetResponseOnHttpContext(context.HttpContext, context.DownstreamResponse);
            }
        }
        public async Task Invoke(DownstreamContext context)
        {
            var dsPath = _replacer
                         .Replace(context.DownstreamReRoute.DownstreamPathTemplate, context.TemplatePlaceholderNameAndValues);

            if (dsPath.IsError)
            {
                _logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error");

                SetPipelineError(context, dsPath.Errors);
                return;
            }

            UriBuilder uriBuilder;

            if (ServiceFabricRequest(context))
            {
                uriBuilder = CreateServiceFabricUri(context, dsPath);
            }
            else
            {
                uriBuilder = new UriBuilder(context.DownstreamRequest.RequestUri)
                {
                    Path   = dsPath.Data.Value,
                    Scheme = context.DownstreamReRoute.DownstreamScheme
                };
            }

            context.DownstreamRequest.RequestUri = uriBuilder.Uri;

            _logger.LogDebug("downstream url is {downstreamUrl.Data.Value}", context.DownstreamRequest.RequestUri);

            await _next.Invoke(context);
        }
Ejemplo n.º 8
0
        public async Task Invoke(DownstreamContext context)
        {
            try
            {
                //try and get the global request id and set it for logs...
                //should this basically be immutable per request...i guess it should!
                //first thing is get config
                var configuration = _configRepo.Get();

                if (configuration.IsError)
                {
                    throw new Exception($"{MiddlewareName} setting pipeline errors. IOcelotConfigurationProvider returned {configuration.Errors.ToErrorString()}");
                }

                TrySetGlobalRequestId(context, configuration.Data);

                context.Configuration = configuration.Data;

                Logger.LogDebug("ocelot pipeline started");

                await _next.Invoke(context);
            }
            catch (Exception e)
            {
                Logger.LogDebug("error calling middleware");

                var message = CreateMessage(context, e);

                Logger.LogError(message, e);

                SetInternalServerErrorOnResponse(context);
            }

            Logger.LogDebug("ocelot pipeline finished");
        }
Ejemplo n.º 9
0
        public async Task Invoke(DownstreamContext context)
        {
            await _next.Invoke(context);

            if (context.IsError)
            {//自定义输出结果
                var errmsg     = context.Errors[0].Message;
                int httpstatus = _codeMapper.Map(context.Errors);
                var errResult  = new BaseResult()
                {
                    errcode = httpstatus, errmsg = errmsg
                };
                var message = errResult.ToJson();
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                await context.HttpContext.Response.WriteAsync(message);

                return;
            }
            else if (context.HttpContext.Response.StatusCode != (int)HttpStatusCode.OK)
            {//标记失败,不做任何处理,自定义扩展时预留
            }
            else if (context.DownstreamResponse == null)
            {//添加如果管道强制终止,不做任何处理,修复未将对象实例化错误
            }
            else
            {//继续请求下游地址返回
                Logger.LogDebug("no pipeline errors, setting and returning completed response");
                await _responder.SetResponseOnHttpContext(context.HttpContext, context.DownstreamResponse);
            }
        }
Ejemplo n.º 10
0
        public async Task Invoke(DownstreamContext context)
        {
            await _next.Invoke(context);

            if (context.IsError)
            {
                var errmsg     = context.Errors[0].Message;
                int httpstatus = _codeMapper.Map(context.Errors);
                var errResult  = new ResultMsg()
                {
                    Success = false, Code = httpstatus, Msg = errmsg
                };
                var message = errResult.ToJson().ToLower();
                context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
                context.HttpContext.Response.StatusCode  = (int)HttpStatusCode.OK;
                await context.HttpContext.Response.WriteAsync(message);

                return;
            }
            else if (context.DownstreamResponse == null)//如果管道强制终止,不做任何处理,修复未将对象实例化错误
            {
            }
            else // 继续请求下游地址返回
            {
                Logger.LogDebug("no pipeline errors, setting and returning completed response");
                await _responder.SetResponseOnHttpContext(context.HttpContext, context.DownstreamResponse);
            }
        }
        public async Task Invoke(DownstreamContext context)
        {
            var dsPath = _replacer
                         .Replace(context.DownstreamReRoute.DownstreamPathTemplate, context.TemplatePlaceholderNameAndValues);

            if (dsPath.IsError)
            {
                _logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error");

                SetPipelineError(context, dsPath.Errors);
                return;
            }

            context.DownstreamRequest.Scheme = context.DownstreamReRoute.DownstreamScheme;

            if (ServiceFabricRequest(context))
            {
                var pathAndQuery = CreateServiceFabricUri(context, dsPath);
                context.DownstreamRequest.AbsolutePath = pathAndQuery.path;
                context.DownstreamRequest.Query        = pathAndQuery.query;
            }
            else
            {
                context.DownstreamRequest.AbsolutePath = dsPath.Data.Value;
            }

            _logger.LogDebug("downstream url is {context.DownstreamRequest}", context.DownstreamRequest);

            await _next.Invoke(context);
        }
Ejemplo n.º 12
0
        public async Task Invoke(DownstreamContext context)
        {
            if (!context.DownstreamReRoute.IsCached)
            {
                await _next.Invoke(context);

                return;
            }

            var    downstreamUrlKey          = $"{context.DownstreamRequest.Method}-{context.DownstreamRequest.OriginalString}";
            string downStreamRequestCacheKey = _cacheGeneratot.GenerateRequestCacheKey(context);

            Logger.LogDebug($"Started checking cache for {downstreamUrlKey}");

            var cached = _outputCache.Get(downStreamRequestCacheKey, context.DownstreamReRoute.CacheOptions.Region);

            if (cached != null)
            {
                Logger.LogDebug($"cache entry exists for {downstreamUrlKey}");

                var response = CreateHttpResponseMessage(cached);
                SetHttpResponseMessageThisRequest(context, response);

                Logger.LogDebug($"finished returned cached response for {downstreamUrlKey}");

                return;
            }

            Logger.LogDebug($"no resonse cached for {downstreamUrlKey}");

            await _next.Invoke(context);

            if (context.IsError)
            {
                Logger.LogDebug($"there was a pipeline error for {downstreamUrlKey}");

                return;
            }

            cached = await CreateCachedResponse(context.DownstreamResponse);

            _outputCache.Add(downStreamRequestCacheKey, cached, TimeSpan.FromSeconds(context.DownstreamReRoute.CacheOptions.TtlSeconds), context.DownstreamReRoute.CacheOptions.Region);

            Logger.LogDebug($"finished response added to cache for {downstreamUrlKey}");
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 当下游协议是RPC时被调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        // ReSharper disable once UnusedMember.Global
        public async Task Invoke(DownstreamContext context)
        {
            IRelayHttpRouteRpc relayHttpRouteRpc = new DefaultRelayHttpRouteRpc(ClientProxy.IRemoteInvokeService, ClientProxy.ITypeConvertibleService);

            var httpContent = relayHttpRouteRpc.HttpRouteRpc(ClientProxy.GenerateAll(new Uri("http://127.0.0.1:8500")),
                                                             new Uri(context.DownstreamRequest.ToUri()),
                                                             context.DownstreamRequest.Headers); // 目前尚未处理Headers消息头

            context.DownstreamResponse = new DownstreamResponse(httpContent, HttpStatusCode.OK, context.DownstreamRequest.Headers);
            await _next.Invoke(context);
        }
Ejemplo n.º 14
0
        public async Task Invoke(DownstreamContext context)
        {
            var downstreamScheme = context.DownstreamReRoute.DownstreamScheme;

            if (downstreamScheme.ToLower() != "grpc")
            {
                await _next.Invoke(context);

                return;
            }
        }
        public async Task Invoke(DownstreamContext context)
        {
            var response = _replacer
                           .Replace(context.DownstreamReRoute.DownstreamPathTemplate.Value, context.TemplatePlaceholderNameAndValues);

            if (response.IsError)
            {
                Logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error");

                SetPipelineError(context, response.Errors);
                return;
            }

            if (!string.IsNullOrEmpty(context.DownstreamReRoute.DownstreamScheme))
            {
                context.DownstreamRequest.Scheme = context.DownstreamReRoute.DownstreamScheme;
            }

            if (ServiceFabricRequest(context))
            {
                var pathAndQuery = CreateServiceFabricUri(context, response);
                context.DownstreamRequest.AbsolutePath = pathAndQuery.path;
                context.DownstreamRequest.Query        = pathAndQuery.query;
            }
            else
            {
                var dsPath = response.Data;

                if (ContainsQueryString(dsPath))
                {
                    context.DownstreamRequest.AbsolutePath = GetPath(dsPath);

                    if (string.IsNullOrEmpty(context.DownstreamRequest.Query))
                    {
                        context.DownstreamRequest.Query = GetQueryString(dsPath);
                    }
                    else
                    {
                        context.DownstreamRequest.Query += GetQueryString(dsPath).Replace('?', '&');
                    }
                }
                else
                {
                    RemoveQueryStringParametersThatHaveBeenUsedInTemplate(context);

                    context.DownstreamRequest.AbsolutePath = dsPath.Value;
                }
            }

            Logger.LogDebug($"Downstream url is {context.DownstreamRequest}");

            await _next.Invoke(context);
        }
        public async Task Invoke(DownstreamContext context)
        {
            var preFAndRs = context.DownstreamReRoute.UpstreamHeadersFindAndReplace;

            //todo - this should be on httprequestmessage not httpcontext?
            _preReplacer.Replace(context.HttpContext, preFAndRs);

            await _next.Invoke(context);

            var postFAndRs = context.DownstreamReRoute.DownstreamHeadersFindAndReplace;

            _postReplacer.Replace(context.DownstreamResponse, postFAndRs, context.DownstreamRequest);
        }
 public async Task Invoke(DownstreamContext context)
 {
     if (!context.IsError && context.HttpContext.Request.Method.ToUpper() != "OPTIONS" &&
         IsAuthenticatedRoute(context.DownstreamReRoute))
     {
         if (!_options.ClientAuthorization)
         {
             Logger.LogInformation($"未启用客户端授权管道");
             await _next.Invoke(context);
         }
         else
         {
             Logger.LogInformation($"{context.HttpContext.Request.Path} 是认证路由. {MiddlewareName} 开始校验授权信息");
             #region 提取客户端ID
             var clientId    = "client_cjy";
             var path        = context.DownstreamReRoute.UpstreamPathTemplate.OriginalValue; //路由地址
             var clientClaim = context.HttpContext.User.Claims.FirstOrDefault(p => p.Type == _options.ClientKey);
             if (!string.IsNullOrEmpty(clientClaim?.Value))
             {//从Claims中提取客户端id
                 clientId = clientClaim?.Value;
             }
             #endregion
             if (await _ahphAuthenticationProcessor.CheckClientAuthenticationAsync(clientId, path))
             {
                 await _next.Invoke(context);
             }
             else
             {//未授权直接返回错误
                 var error = new UnauthenticatedError($"请求认证路由 {context.HttpContext.Request.Path}客户端未授权");
                 Logger.LogWarning($"路由地址 {context.HttpContext.Request.Path} 自定义认证管道校验失败. {error}");
                 SetPipelineError(context, error);
             }
         }
     }
     else
     {
         await _next.Invoke(context);
     }
 }
        public async Task Invoke(DownstreamContext context)
        {
            var downstreamRequest = await _requestMapper.Map(context.HttpContext.Request);

            if (downstreamRequest.IsError)
            {
                SetPipelineError(context, downstreamRequest.Errors);
                return;
            }

            context.DownstreamRequest = new DownstreamRequest(downstreamRequest.Data);

            await _next.Invoke(context);
        }
Ejemplo n.º 19
0
        public async Task Invoke(DownstreamContext context)
        {
            await _next.Invoke(context);

            if (context.IsError)
            {
                Logger.LogWarning($"{context.Errors.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{context.HttpContext.Request.Path}, request method: {context.HttpContext.Request.Method}");

                SetErrorResponse(context.HttpContext, context.Errors);
            }
            else
            {
                Logger.LogDebug("no pipeline errors, setting and returning completed response");
                await _responder.SetResponseOnHttpContext(context.HttpContext, context.DownstreamResponse);
            }
        }
Ejemplo n.º 20
0
        public async Task Invoke(DownstreamContext context)
        {
            await _next.Invoke(context);

            if (context.IsError)
            {
                var errors = context.Errors;
                _logger.LogError($"{errors.Count} pipeline errors found in {MiddlewareName}. Setting error response status code");
                SetErrorResponse(context.HttpContext, errors);
            }
            else
            {
                _logger.LogDebug("no pipeline errors, setting and returning completed response");
                await _responder.SetResponseOnHttpContext(context.HttpContext, context.DownstreamResponse);
            }
        }
Ejemplo n.º 21
0
        public async Task Invoke(DownstreamContext context)
        {
            var loadBalancer = await _loadBalancerHouse.Get(context.DownstreamReRoute, context.Configuration.ServiceProviderConfiguration);

            if (loadBalancer.IsError)
            {
                Logger.LogDebug("there was an error retriving the loadbalancer, setting pipeline error");
                SetPipelineError(context, loadBalancer.Errors);
                return;
            }

            var hostAndPort = await loadBalancer.Data.Lease(context);

            if (hostAndPort.IsError)
            {
                Logger.LogDebug("there was an error leasing the loadbalancer, setting pipeline error");
                SetPipelineError(context, hostAndPort.Errors);
                return;
            }

            context.DownstreamRequest.Host = hostAndPort.Data.DownstreamHost;

            if (hostAndPort.Data.DownstreamPort > 0)
            {
                context.DownstreamRequest.Port = hostAndPort.Data.DownstreamPort;
            }

            if (!string.IsNullOrEmpty(hostAndPort.Data.Scheme))
            {
                context.DownstreamRequest.Scheme = hostAndPort.Data.Scheme;
            }

            try
            {
                await _next.Invoke(context);
            }
            catch (Exception)
            {
                Logger.LogDebug("Exception calling next middleware, exception will be thrown to global handler");
                throw;
            }
            finally
            {
                loadBalancer.Data.Release(hostAndPort.Data);
            }
        }
Ejemplo n.º 22
0
        public async Task Invoke(DownstreamContext context)
        {
            if (context.DownstreamReRoute.ClaimsToClaims.Any())
            {
                _logger.LogDebug("this route has instructions to convert claims to other claims");

                var result = _addClaimsToRequest.SetClaimsOnContext(context.DownstreamReRoute.ClaimsToClaims, context.HttpContext);

                if (result.IsError)
                {
                    _logger.LogDebug("error converting claims to other claims, setting pipeline error");

                    SetPipelineError(context, result.Errors);
                    return;
                }
            }
            await _next.Invoke(context);
        }
Ejemplo n.º 23
0
 public async Task Invoke(DownstreamContext context)
 {
     if (!context.IsError && context.HttpContext.Request.Method.ToUpper() != "OPTIONS")
     {
         Console.WriteLine("======》 自定义中间件");
         Console.WriteLine("======》 自定义业务逻辑处理");
         // 1、处理统一结果
         // resutList resultMap
         // 2、统一日志记录
         // 3、做链路监控
         // 4、性能监控
         // 5、流量统计
     }
     else
     {
         await _next.Invoke(context);
     }
 }
Ejemplo n.º 24
0
        public async Task Invoke(DownstreamContext context)
        {
            var response = await _requester.GetResponse(context);

            if (response.IsError)
            {
                Logger.LogDebug("IHttpRequester returned an error, setting pipeline error");

                SetPipelineError(context, response.Errors);
                return;
            }

            Logger.LogDebug("setting http response message");

            context.DownstreamResponse = new DownstreamResponse(response.Data);

            await _next.Invoke(context);
        }
Ejemplo n.º 25
0
        public async Task Invoke(DownstreamContext context)
        {
            var response = _replacer
                           .Replace(context.DownstreamReRoute.DownstreamPathTemplate, context.TemplatePlaceholderNameAndValues);

            if (response.IsError)
            {
                Logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error");

                SetPipelineError(context, response.Errors);
                return;
            }

            context.DownstreamRequest.Scheme = context.DownstreamReRoute.DownstreamScheme;

            if (ServiceFabricRequest(context))
            {
                var pathAndQuery = CreateServiceFabricUri(context, response);
                context.DownstreamRequest.AbsolutePath = pathAndQuery.path;
                context.DownstreamRequest.Query        = pathAndQuery.query;
            }
            else
            {
                var dsPath = response.Data;

                if (ContainsQueryString(dsPath))
                {
                    context.DownstreamRequest.AbsolutePath = GetPath(dsPath);
                    context.DownstreamRequest.Query        = GetQueryString(dsPath);

                    // todo - do we need to add anything from the request query string onto the query from the
                    // templae?
                }
                else
                {
                    context.DownstreamRequest.AbsolutePath = dsPath.Value;
                }
            }

            Logger.LogDebug($"Downstream url is {context.DownstreamRequest}");

            await _next.Invoke(context);
        }
        public async Task Invoke(DownstreamContext context)
        {
            if (context.DownstreamReRoute.ClaimsToPath.Any())
            {
                Logger.LogInformation($"{context.DownstreamReRoute.DownstreamPathTemplate.Value} has instructions to convert claims to path");
                var response = _changeDownstreamPathTemplate.ChangeDownstreamPath(context.DownstreamReRoute.ClaimsToPath, context.HttpContext.User.Claims,
                                                                                  context.DownstreamReRoute.DownstreamPathTemplate, context.TemplatePlaceholderNameAndValues);

                if (response.IsError)
                {
                    Logger.LogWarning("there was an error setting queries on context, setting pipeline error");

                    SetPipelineError(context, response.Errors);
                    return;
                }
            }

            await _next.Invoke(context);
        }
        public async Task Invoke(DownstreamContext context)
        {
            if (context.DownstreamReRoute.ClaimsToQueries.Any())
            {
                Logger.LogInformation($"{context.DownstreamReRoute.DownstreamPathTemplate.Value} has instructions to convert claims to queries");

                var response = _addQueriesToRequest.SetQueriesOnDownstreamRequest(context.DownstreamReRoute.ClaimsToQueries, context.HttpContext.User.Claims, context.DownstreamRequest);

                if (response.IsError)
                {
                    Logger.LogWarning("there was an error setting queries on context, setting pipeline error");

                    SetPipelineError(context, response.Errors);
                    return;
                }
            }

            await _next.Invoke(context);
        }
Ejemplo n.º 28
0
        public async Task Invoke(DownstreamContext context)
        {
            if (_securityPolicies != null)
            {
                foreach (var policie in _securityPolicies)
                {
                    var result = await policie.Security(context);

                    if (!result.IsError)
                    {
                        continue;
                    }

                    this.SetPipelineError(context, result.Errors);
                    return;
                }
            }

            await _next.Invoke(context);
        }
        public async Task Invoke(DownstreamContext context)
        {
            if (context.DownstreamReRoute.ClaimsToHeaders.Any())
            {
                _logger.LogDebug($"{ context.DownstreamReRoute.DownstreamPathTemplate.Value} has instructions to convert claims to headers");

                var response = _addHeadersToRequest.SetHeadersOnDownstreamRequest(context.DownstreamReRoute.ClaimsToHeaders, context.HttpContext.User.Claims, context.DownstreamRequest);

                if (response.IsError)
                {
                    _logger.LogDebug("Error setting headers on context, setting pipeline error");

                    SetPipelineError(context, response.Errors);
                    return;
                }

                _logger.LogDebug("headers have been set on context");
            }

            await _next.Invoke(context);
        }
        public async Task Invoke(DownstreamContext context)
        {
            var preFAndRs = context.DownstreamReRoute.UpstreamHeadersFindAndReplace;

            //todo - this should be on httprequestmessage not httpcontext?
            _preReplacer.Replace(context.HttpContext, preFAndRs);

            _addHeadersToRequest.SetHeadersOnDownstreamRequest(context.DownstreamReRoute.AddHeadersToUpstream, context.HttpContext);

            await _next.Invoke(context);

            if (context.IsError)
            {
                return;
            }

            var postFAndRs = context.DownstreamReRoute.DownstreamHeadersFindAndReplace;

            _postReplacer.Replace(context.DownstreamResponse, postFAndRs, context.DownstreamRequest);

            _addHeadersToResponse.Add(context.DownstreamReRoute.AddHeadersToDownstream, context.DownstreamResponse);
        }