Beispiel #1
0
        private static IDictionary <string, string> ExtractHeaders(HttpHeadersCollection headers)
        {
            Dictionary <string, string> result =
                headers.AllKeys.ToDictionary(x => x, x => headers.Get(x));

            return(result);
        }
Beispiel #2
0
        private static IDictionary <string, string> ExtractHeaders(HttpHeadersCollection headers)
        {
            Dictionary <string, string> result =
                headers.HeaderNames.ToDictionary(x => x, x => headers[x]);

            return(result);
        }
Beispiel #3
0
 public GrpcHttpResponseData(FunctionContext functionContext, HttpStatusCode statusCode, Stream body)
     : base(functionContext)
 {
     _body      = body ?? throw new ArgumentNullException(nameof(body));
     _headers   = new HttpHeadersCollection();
     StatusCode = statusCode;
     Cookies    = new GrpcHttpCookies(_rpcHttp.Cookies);
 }
Beispiel #4
0
        private static HttpRequestData GetRequestWithAuthHeader(string value)
        {
            var ctx     = MockFunction.GetContext();
            var req     = MockFunction.GetRequest(null, ctx);
            var headers = new HttpHeadersCollection();

            headers.Add("Authorization", value);
            req.Headers.Returns(headers);
            return(req);
        }
Beispiel #5
0
        public static Guid GetUserId(HttpHeadersCollection headers)
        {
            var userId = headers.GetValues("user-id").FirstOrDefault();

            if (userId != null)
            {
                return(Guid.Parse(userId));
            }
            return(default(Guid));
        }
Beispiel #6
0
 public TestHttpRequestData(FunctionContext functionContext, Stream body = null, string method = "GET", string url = null)
     : base(functionContext)
 {
     Body       = body ?? new MemoryStream();
     Headers    = new HttpHeadersCollection();
     Cookies    = new List <IHttpCookie>();
     Url        = new Uri(url ?? "https://localhost");
     Identities = new List <ClaimsIdentity>();
     Method     = method;
 }
        public void HeaderValidationResult(string name, string value)
        {
            IEnumerable <KeyValuePair <string, string> > headers = new Dictionary <string, string>()
            {
                { name, value },
            };

            var headersCollection = new HttpHeadersCollection(headers);


            Assert.Single(headersCollection);
        }
Beispiel #8
0
        protected virtual HttpContext BuildGraphQLHttpContext(
            string requestHttpMethod,
            Uri requestUri,
            HttpHeadersCollection requestHeadersCollection,
            string requestBody            = null,
            string requestBodyContentType = "application/json",
            IEnumerable <ClaimsIdentity> claimsIdentities = null
            )
        {
            //Initialize the root Http Context (Container)...
            var httpContext = new DefaultHttpContext();

            //Initialize the Http Request...
            var httpRequest = httpContext.Request;

            httpRequest.Scheme      = requestUri.Scheme;
            httpRequest.Path        = new PathString(requestUri.AbsolutePath);
            httpRequest.Method      = requestHttpMethod ?? HttpMethod.Post.Method;
            httpRequest.QueryString = new QueryString(requestUri.Query);

            //Ensure we marshall across all Headers from teh Client Request...
            if (requestHeadersCollection?.Any() == true)
            {
                foreach (var header in requestHeadersCollection)
                {
                    httpRequest.Headers.Add(header.Key, new StringValues(header.Value.ToArray()));
                }
            }

            if (!string.IsNullOrEmpty(requestBody))
            {
                //Initialize a valid Stream for the Request (must be tracked & Disposed of!)
                var requestBodyBytes = Encoding.UTF8.GetBytes(requestBody);
                httpRequest.Body          = new MemoryStream(requestBodyBytes);
                httpRequest.ContentType   = requestBodyContentType;
                httpRequest.ContentLength = requestBodyBytes.Length;
            }

            //Initialize the Http Response...
            var httpResponse = httpContext.Response;

            //Initialize a valid Stream for the Response (must be tracked & Disposed of!)
            //NOTE: Default Body is a NullStream...which ignores all Reads/Writes.
            httpResponse.Body = new MemoryStream();

            //Proxy over any possible authentication claims if available
            if (claimsIdentities?.Any() == true)
            {
                httpContext.User = new ClaimsPrincipal(claimsIdentities);
            }

            return(httpContext);
        }
        internal static Scope CreateScope(IHttpControllerContext controllerContext, out AspNetTags tags)
        {
            Scope scope = null;

            tags = null;

            try
            {
                if (!Tracer.Instance.Settings.IsIntegrationEnabled(IntegrationId))
                {
                    // integration disabled, don't create a scope, skip this trace
                    return(null);
                }

                var         tracer            = Tracer.Instance;
                var         request           = controllerContext.Request;
                SpanContext propagatedContext = null;
                var         tagsFromHeaders   = Enumerable.Empty <KeyValuePair <string, string> >();

                if (request != null && tracer.ActiveScope == null)
                {
                    try
                    {
                        // extract propagated http headers
                        var headers           = request.Headers;
                        var headersCollection = new HttpHeadersCollection(headers);

                        propagatedContext = SpanContextPropagator.Instance.Extract(headersCollection);
                        tagsFromHeaders   = SpanContextPropagator.Instance.ExtractHeaderTags(headersCollection, tracer.Settings.HeaderTags, SpanContextPropagator.HttpRequestHeadersTagPrefix);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error extracting propagated HTTP headers.");
                    }
                }

                tags  = new AspNetTags();
                scope = tracer.StartActiveWithTags(OperationName, propagatedContext, tags: tags);
                UpdateSpan(controllerContext, scope.Span, tags, tagsFromHeaders);

                tags.SetAnalyticsSampleRate(IntegrationId, tracer.Settings, enabledWithGlobalSetting: true);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error creating scope.");
            }

            return(scope);
        }
    public static HttpResponseData BuildHttpResponseData(
        FunctionContext functionContext = null)
    {
        functionContext ??= BuildFunctionContext();

        var responseData = Substitute.For <HttpResponseData>(functionContext);

        var responseHeaders = new HttpHeadersCollection();

        responseData.Headers.Returns(responseHeaders);

        var responseBody = new MemoryStream();

        responseData.Body.Returns(responseBody);

        return(responseData);
    }
        public void When_formatting_multiple_headers_should_return_human_readable_representation()
        {
            string expectedText = $"Headers: Content-Type: text/plain{Environment.NewLine}Accept: text/plain, text/html";
            var    headers      = new HttpHeadersCollection
            {
                { "Content-Type", "text/plain" },
                { "Accept", new[] { "text/plain", "text/html" } }
            };

            _sut = new HttpHeadersMatcher(headers);

            // Act
            string displayText = _sut.ToString();

            // Assert
            displayText.Should().Be(expectedText);
        }
        public async Task <ClaimsPrincipal?> GetUser(HttpHeadersCollection headers)
        {
            const string bearerPrefix = "Bearer ";

            if (!headers.TryGetValues(HeaderNames.Authorization, out var authorizationHeaders) ||
                authorizationHeaders == null || !authorizationHeaders.Any())
            {
                return(null);
            }

            var authorizationHeader = authorizationHeaders.First();

            if (!authorizationHeader.StartsWith(bearerPrefix, StringComparison.OrdinalIgnoreCase))
            {
                logger.LogWarning($"Bearer prefix not found in authorization token");
                return(null);
            }

            var token = authorizationHeader[bearerPrefix.Length..];
Beispiel #13
0
 /// <summary>
 /// Matches a request by HTTP headers.
 /// </summary>
 /// <param name="builder">The request matching builder instance.</param>
 /// <param name="headers">The headers.</param>
 /// <returns>The request matching builder instance.</returns>
 public static RequestMatching Headers(this RequestMatching builder, string headers)
 {
     return(builder.Headers(HttpHeadersCollection.Parse(headers)));
 }
Beispiel #14
0
 public HttpRequestMessageProperty()
 {
     _httpHeadersCollection = new HttpHeadersCollection();
 }
        internal async Task<SimpleHttpResponse> SendAsync(HttpContent requestContent)
        {
            var requestMessage = new HttpRequestMessage { Method = this.Method, RequestUri = this.Uri };

            if (this.Method == HttpMethod.Post || this.Method == HttpMethod.Put)
            {
                if (requestContent != null)
                {
                    requestMessage.Content = requestContent;
                }
            }

            requestMessage.Headers.Clear();
            foreach (var header in this.Headers)
            {
                requestMessage.Headers.Add(header.Key, header.Value);
            }

            if (this.HttpProxy != null)
            {
                this.handler.Proxy = new SimpleProxy(this.HttpProxy);
            }

            this.handler.SkipCertificateValidation = this.SkipCertificateValidation;

            this.client.Timeout = this.Timeout;
            var startTime = DateTime.Now;

            try
            {
                var result = await this.client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, this.cancellationToken).ConfigureAwait(false);

                var headers = new HttpHeadersCollection(result.Headers);

                HttpContent content = null;
                if (result.Content != null)
                {
                    headers.AddRange(result.Content.Headers);

                    content = result.Content;
                }

                return new SimpleHttpResponse(content, headers, result.StatusCode);
            }
            catch (Exception ex)
            {
                var tcex = ex as TaskCanceledException;
                if (tcex == null)
                {
                    throw;
                }

                if (this.cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException("The operation was canceled by user request.", tcex, this.cancellationToken);
                }

                if (DateTime.Now - startTime > this.Timeout)
                {
                    throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The task failed to complete in the given timeout period ({0}).", this.Timeout), tcex);
                }

                throw;
            }
        }