Exemplo n.º 1
0
        /// <summary>
        /// Adds the headers necessary to trigger HMAC signing if we don't already have an Authentication header.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="headers"></param>
        public static void AddHmacClientHeaders(this IHmacClient client, HttpRequestHeaders headers)
        {
            var auth = headers.Authorization;

            if (auth != null)
            {
                return;
            }

            // Only bother if we don't have an authentication header?
            var clientId = client.ClientId;

            if (!string.IsNullOrEmpty(clientId))
            {
                // Mark it so we know to sign the message
                headers.Add(HmacAuthentication.ClientIdHeader, clientId);

                // See if we have any custom headers
                var customHeaders = client.AddCustomHeaders(headers);
                if (!string.IsNullOrEmpty(customHeaders))
                {
                    // Ok, mark it so the signer knows to include them in the signature.
                    headers.Add(HmacAuthentication.CustomHeaders, customHeaders.Trim());
                }
            }
        }
Exemplo n.º 2
0
        public void CopyToMovesDataIntoArray()
        {
            IDictionary <string, StringValues> headers = new HttpRequestHeaders();

            headers.Add("host", new[] { "localhost" });
            headers.Add("Content-Length", new[] { "0" });
            headers.Add("custom", new[] { "value" });

            var entries = new KeyValuePair <string, StringValues> [5];

            headers.CopyTo(entries, 1);

            Assert.Null(entries[0].Key);
            Assert.Equal(new StringValues(), entries[0].Value);

            Assert.Equal("Host", entries[1].Key);
            Assert.Equal(new[] { "localhost" }, entries[1].Value);

            Assert.Equal("Content-Length", entries[2].Key);
            Assert.Equal(new[] { "0" }, entries[2].Value);

            Assert.Equal("custom", entries[3].Key);
            Assert.Equal(new[] { "value" }, entries[3].Value);

            Assert.Null(entries[4].Key);
            Assert.Equal(new StringValues(), entries[4].Value);
        }
Exemplo n.º 3
0
 private static void InjectContext(HttpRequestHeaders headers, string traceId, string spanId, string samplingPriority, string origin)
 {
     headers.Add(HttpHeaderNames.TraceId, traceId);
     headers.Add(HttpHeaderNames.ParentId, spanId);
     headers.Add(HttpHeaderNames.SamplingPriority, samplingPriority);
     headers.Add(HttpHeaderNames.Origin, origin);
 }
Exemplo n.º 4
0
        /// <summary>
        /// Set <see cref="HttpRequestHeaders"/> using the <see cref="ApiHeaders"/>. This initially clears <paramref name="headers"/>
        /// </summary>
        /// <param name="headers">The <see cref="HttpRequestHeaders"/> to set</param>
        /// <param name="instanceId">The <see cref="Models.Instance.Id"/> for the request</param>
        public void SetRequestHeaders(HttpRequestHeaders headers, long?instanceId = null)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }
            if (instanceId.HasValue && InstanceId.HasValue && instanceId != InstanceId)
            {
                throw new InvalidOperationException("Specified instance ID in constructor and SetRequestHeaders!");
            }

            headers.Clear();
            headers.Accept.Add(new MediaTypeWithQualityHeaderValue(ApplicationJson));
            if (IsTokenAuthentication)
            {
                headers.Authorization = new AuthenticationHeaderValue(JwtAuthenticationScheme, Token);
            }
            else
            {
                headers.Authorization = new AuthenticationHeaderValue(PasswordAuthenticationScheme, Password);
                headers.Add(UsernameHeader, Username);
            }

            headers.UserAgent.Add(new ProductInfoHeaderValue(UserAgent));
            headers.Add(ApiVersionHeader, new ProductHeaderValue(AssemblyName.Name, ApiVersion.ToString()).ToString());
            instanceId = instanceId ?? InstanceId;
            if (instanceId.HasValue)
            {
                headers.Add(InstanceIdHeader, instanceId.ToString());
            }
        }
        public void has_positive()
        {
            headers.Add("a", new string[] { "1", "2" });

            request.HasHeader("a").ShouldBeTrue();
            request.HasHeader("A").ShouldBeTrue();
        }
Exemplo n.º 6
0
        /// <summary>
        ///     Applies X-Forwarded.* headers to the outgoing header collection
        ///     with an additional PathBase parameter.
        /// </summary>
        /// <param name="outgoingHeaders">The outgoing HTTP request
        /// headers.</param>
        /// <param name="for">The client IP address.</param>
        /// <param name="host">The host of the request.</param>
        /// <param name="proto">The protocol of the incoming request.</param>
        /// <param name="pathBase">The base path of the incoming
        /// request.</param>
        public static void ApplyXForwardedHeaders(
            this HttpRequestHeaders outgoingHeaders,
            IPAddress @for,
            HostString host,
            string proto,
            PathString pathBase)
        {
            if (@for != null)
            {
                var forString = @for.AddressFamily == AddressFamily.InterNetworkV6
                    ? $"\"[{@for}]\""
                    : @for.ToString();
                outgoingHeaders.Add(XForwardedFor, forString);
            }

            if (host.HasValue)
            {
                outgoingHeaders.Add(XForwardedHost, host.Value);
            }

            if (!string.IsNullOrWhiteSpace(proto))
            {
                outgoingHeaders.Add(XForwardedProto, proto);
            }

            if (!string.IsNullOrWhiteSpace(pathBase))
            {
                outgoingHeaders.Add(XForwardedPathBase, pathBase);
            }
        }
Exemplo n.º 7
0
 public static void SetHeaderValue(this HttpRequestHeaders Headers, string code)
 {
     Headers.Add("sobeyhive-http-system", "INGESTSERVER");
     Headers.Add("sobeyhive-http-site", "S1");
     Headers.Add("sobeyhive-http-tool", "INGESTSERVER");
     Headers.Add("sobeyhive-http-secret", RSAHelper.RSAstr());
     Headers.Add("current-user-code", code);
 }
Exemplo n.º 8
0
        /// <summary>
        /// SetHikSecurityHeaders
        /// </summary>
        /// <param name="headers">headers</param>
        /// <param name="body">body</param>
        /// <param name="url">url</param>
        /// <param name="data">data</param>
        /// <param name="method">method</param>
        /// <returns></returns>
        public static HttpRequestHeaders SetHikSecurityHeaders(this HttpRequestHeaders headers, string body, string url, object data, string method)
        {
            var formData = new Dictionary <string, string>();

            if (data != null)
            {
                Type t = data.GetType();

                PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (PropertyInfo p in pi)
                {
                    MethodInfo mi = p.GetGetMethod();

                    if (mi != null && mi.IsPublic)
                    {
                        formData.Add(p.Name, mi.Invoke(data, new Object[] { })?.ToString());
                    }
                }
            }
            headers.Date = DateTimeOffset.Now;
            var securityHeaders = GetHikSecurityHeaders(headers, method, url, formData);
            var allHeaders      = new Dictionary <string, string>();

            foreach (var header in headers)
            {
                if (header.Value?.Count() > 0)
                {
                    if (header.Key.Equals("url"))
                    {
                        continue;
                    }
                    allHeaders.Add(header.Key, header.Value?.FirstOrDefault() ?? "");
                }
            }
            var sign = BuildStringToSign(securityHeaders, allHeaders);

            headers.Add("X-Ca-Signature", HmacSha256(sign));
            if (securityHeaders.Count > 0)
            {
                string secheaders = "";
                foreach (var securityHeader in securityHeaders)
                {
                    secheaders += $@"{securityHeader.Key}:{securityHeader.Value} ,";
                }
                headers.Add("X-Ca-Signature-Headers", secheaders.TrimEnd(','));
            }
            headers.Add("appKey", new List <string>()
            {
                HikSecurityContext.ArtemisAppKey
            });
            headers.Add("appSecret", new List <string>()
            {
                HikSecurityContext.ArtemisAppSecret
            });
            return(headers);
        }
Exemplo n.º 9
0
 protected virtual void AddCommonHeaders(HttpRequestHeaders headers, AccessToken accessToken)
 {
     if (!string.IsNullOrWhiteSpace(accessToken?.Token))
     {
         headers.Add("X-Acrolinx-Auth", accessToken.Token);
     }
     headers.Add("X-Acrolinx-Base-Url", this.acrolinxUrl);
     headers.Add("X-Acrolinx-Client-Locale", this.clientLocale);
     headers.Add("X-Acrolinx-Client", this.clientSignature + "; " + this.clientVersion);
     headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 }
Exemplo n.º 10
0
        public static void SetAvailabilityTestRequestHeaders(this HttpClient httpClient, string testInfoDescriptor, string testInvocationInstanceDescriptor)
        {
            Validate.NotNull(httpClient, nameof(httpClient));
            Validate.NotNullOrWhitespace(testInfoDescriptor, nameof(testInfoDescriptor));
            Validate.NotNullOrWhitespace(testInvocationInstanceDescriptor, nameof(testInvocationInstanceDescriptor));

            HttpRequestHeaders headers = httpClient.DefaultRequestHeaders;

            headers.Add(Format.AvailabilityTest.HttpHeaderNames.TestInfoDescriptor, Format.SpellIfNull(testInfoDescriptor));
            headers.Add(Format.AvailabilityTest.HttpHeaderNames.TestInvocationInstanceDescriptor, Format.SpellIfNull(testInvocationInstanceDescriptor));
        }
Exemplo n.º 11
0
 /// <summary>
 /// An internal method, used for preparing http headers for get and post request.
 /// </summary>
 protected void PrepareHeader(HttpRequestHeaders header)
 {
     header.Add(
         "user-agent",
         "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36"
         );
     header.Add(
         "accept",
         "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"
         );
 }
Exemplo n.º 12
0
        public async Task <bool> FollowUser(string githubAccessToken, string userName)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpRequestHeaders headers = client.DefaultRequestHeaders;
                headers.Add("Authorization", string.Format("token {0}", githubAccessToken));
                headers.Add("User-Agent", "PrimarySchool");
                HttpResponseMessage response = await client.PutAsync($"https://api.github.com/user/following/{userName}", new StringContent(string.Empty));

                return(response.StatusCode == System.Net.HttpStatusCode.NoContent);
            }
        }
Exemplo n.º 13
0
        public static void SetRequestProperties(HttpRequestHeaders headers, UnleashConfig config)
        {
            headers.Add(UNLEASH_APP_NAME_HEADER, config.AppName);
            headers.Add(UNLEASH_INSTANCE_ID_HEADER, config.InstanceId);
            headers.Add("User-Agent", config.AppName);

            config
            .CustomHttpHeaders
            .Keys
            .ToList()
            .ForEach(key => headers.Add(key, config.CustomHttpHeaders[key]));
        }
Exemplo n.º 14
0
        private void SetHeaders(HttpRequestHeaders headers, Dictionary <string, string> newHeaders)
        {
            if (newHeaders != null)
            {
                foreach (var header in newHeaders)
                {
                    headers.Add(header.Key, header.Value);
                }
            }

            headers.Add("sino", "nacos");
        }
 public static void add(this HttpRequestHeaders headers, string name, string value)
 {
     if (!headers.Contains(name))
     {
         headers.Add(name, value);
     }
     else
     {
         headers.Remove(name);
         headers.Add(name, value);
     }
 }
Exemplo n.º 16
0
 private void AddCommonAuthHeaders(HttpRequestHeaders headers, string referrer)
 {
     headers.Add("Accept-Language", "en-US,en;q=0.5");
     headers.Add("Connection", "keep-alive");
     headers.Add("Pragma", "no-cache");
     headers.Add("Cache-Control", "no-cache");
     headers.Host = "account.sonnen.de";
     if (!string.IsNullOrWhiteSpace(referrer))
     {
         headers.Referrer = new Uri(referrer);
     }
     headers.TryAddWithoutValidation("User-Agent", _userAgent);
 }
Exemplo n.º 17
0
        private void SetRequestHeaders(HttpRequestHeaders httpRequestHeaders, string userAgent, string authorizationToken, string etag)
        {
            httpRequestHeaders.Accept.Clear();
            httpRequestHeaders.Add("User-agent", userAgent);
            httpRequestHeaders.Add("Authorization", string.Format("Token {0}", authorizationToken));

            if (!string.IsNullOrEmpty(etag))
            {
                httpRequestHeaders.Add("If-None-Match", string.Format(@"{0}", etag));
            }

            httpRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
Exemplo n.º 18
0
        private static void InjectW3CHeaders(Activity currentActivity, HttpRequestHeaders requestHeaders)
        {
            if (!requestHeaders.Contains(W3C.W3CConstants.TraceParentHeader))
            {
                requestHeaders.Add(W3C.W3CConstants.TraceParentHeader, currentActivity.Id);
            }

            if (!requestHeaders.Contains(W3C.W3CConstants.TraceStateHeader) &&
                currentActivity.TraceStateString != null)
            {
                requestHeaders.Add(W3C.W3CConstants.TraceStateHeader,
                                   currentActivity.TraceStateString);
            }
        }
Exemplo n.º 19
0
        private async Task <HttpResponseMessage> GetServiceConnectionAsync(string urlFragment, string method, string?body, UnidentifiedAccess?unidentifiedAccess, CancellationToken?token = null)
        {
            if (token == null)
            {
                token = CancellationToken.None;
            }

            try
            {
                SignalUrl          signalUrl  = GetRandom(SignalConnectionInformation.SignalServiceUrls);
                string             url        = signalUrl.Url;
                string?            hostHeader = signalUrl.HostHeader;
                Uri                uri        = new Uri(string.Format("{0}{1}", url, urlFragment));
                HttpRequestMessage request    = new HttpRequestMessage(new HttpMethod(method), uri);

                if (body != null)
                {
                    request.Content = new StringContent(body, Encoding.UTF8, "application/json");
                }

                HttpRequestHeaders headers = request.Headers;

                if (unidentifiedAccess != null)
                {
                    headers.Add("Unidentified-Access-Key", Base64.EncodeBytes(unidentifiedAccess.UnidentifiedAccessKey));
                }
                if (CredentialsProvider.Password != null)
                {
                    string authHeader = GetAuthorizationHeader(CredentialsProvider);
                    headers.Add("Authorization", authHeader);
                }

                if (UserAgent != null)
                {
                    headers.Add("X-Signal-Agent", UserAgent);
                }

                if (hostHeader != null)
                {
                    headers.Host = hostHeader;
                }

                return(await httpClient.SendAsync(request, token.Value));
            }
            catch (Exception e)
            {
                Logger.LogError("GetServiceConnectionAsync() failed: {0}\n{1}", e.Message, e.StackTrace);
                throw new PushNetworkException(e);
            }
        }
Exemplo n.º 20
0
 void AddNpmHeaders(IActivityMonitor m, HttpRequestHeaders headers)
 {
     if (NpmInCi)
     {
         headers.Add("npm-in-ci", NpmInCi.ToString().ToLower());   //json type are lowercase
         m.Info("Detected that we are running in CI. Sending to the registry an header indicating it.");
     }
     headers.Add("npm-session", _session);
     headers.Add("user-agent", _userAgent);
     if (_authHeader != null)
     {
         headers.Authorization = _authHeader;
     }
 }
Exemplo n.º 21
0
        private static void Add(this HttpRequestHeaders requestHeaders, string name, string value, Dictionary <string, List <string> > headers)
        {
            List <string> values;

            if (headers != null && headers.TryGetValue(name, out values))
            {
                requestHeaders.Add(name, values);
                headers.Remove(name);
            }
            else
            {
                requestHeaders.Add(name, value);
            }
        }
Exemplo n.º 22
0
 public static void SetSecPolicy(this HttpRequestHeaders headers, string?mode = "cors", string?site = "same-site", string?dest = "empty")
 {
     if (!string.IsNullOrEmpty(mode))
     {
         headers.Add("Sec-Fetch-Mode", mode);
     }
     if (!string.IsNullOrEmpty(site))
     {
         headers.Add("Sec-Fetch-Site", site);
     }
     if (!string.IsNullOrEmpty(dest))
     {
         headers.Add("Sec-Fetch-Dest", dest);
     }
 }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            //REAd configuration file into string
            string filecontent = ReadConfigurationFile("E:/c#/weatherProgram/world/cities.json");

            //parse filecontent

            CityConfig[] cityConfigArray = new JavaScriptSerializer().Deserialize <CityConfig[]>(filecontent);
            Weather      weather         = new Weather();

            Console.WriteLine(weather.str);

            foreach (CityConfig cityConfig in cityConfigArray)
            {
                Console.WriteLine(cityConfig.city);

                float tempkdp = weather.GetCurrentTemperature(cityConfig.city, cityConfig.countrycode);
                Console.WriteLine("temperature :  " + tempkdp);
                //body
                // HttpClient post

                HttpClient httpClient = new HttpClient();
                // (httpClient.DefaultRequestHeaders).Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpRequestHeaders httpRequestHeaders = httpClient.DefaultRequestHeaders;
                // HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> httpHeaderValueCollection = httpRequestHeaders.Accept;
                //  MediaTypeWithQualityHeaderValue mediaTypeWithQualityHeaderValue = new MediaTypeWithQualityHeaderValue("application/json");
                //  httpHeaderValueCollection.Add(mediaTypeWithQualityHeaderValue);
                httpRequestHeaders.Add("X-Insert-Key", "jzsjmfl5Qmntrkfrn28XL5VOTVkYU3ju");
                // httpRequestHeaders.Add("Content-Type", "application/json");
                httpRequestHeaders.Add("xyz", "abc");

                StringContent content = new StringContent("[{\"city\":\"" + cityConfig.city + "\", \"countryCode\":\"" + cityConfig.countrycode + "\" , \"eventType\":\"Temperature\" , \"temperature\":" + tempkdp + "}]", Encoding.UTF8, "application/json");
                Console.WriteLine(content.ReadAsStringAsync().Result);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var result = httpClient.PostAsync("https://insights-collector.newrelic.com/v1/accounts/1245525/events", content).Result;
                if (result.IsSuccessStatusCode)
                {
                    Console.WriteLine("SUCCESSFULLY POSTED DATA TO NEWRELIC");
                }
                else
                {
                    Console.WriteLine("FAILED TO SNED");
                    Console.WriteLine(result.ReasonPhrase);
                }
            }

            Console.ReadKey();
        }
 protected void FillRequestHeadersWithCommonHeaders(HttpRequestHeaders headers)
 {
     foreach (var item in _options.CommonHeaders)
     {
         headers.Add(item.Key, item.Value);
     }
 }
Exemplo n.º 25
0
        // Generates a random expected response content length and adds it to the request headers
        public int SetExpectedResponseContentLengthHeader(HttpRequestHeaders headers, int minLength = 0)
        {
            int expectedResponseContentLength = _random.Next(minLength, Math.Max(minLength, MaxContentLength));

            headers.Add(StressServer.ExpectedResponseContentLength, expectedResponseContentLength.ToString());
            return(expectedResponseContentLength);
        }
Exemplo n.º 26
0
 /// <summary>
 /// Sets test mode header.
 /// </summary>
 /// <param name="headers">The http request header.</param>
 /// <param name="value">The header value.</param>
 public static void SetTestMode(this HttpRequestHeaders headers, string value)
 {
     if (!string.IsNullOrWhiteSpace(value))
     {
         headers.Add("x-bz-test-mode", value);
     }
 }
Exemplo n.º 27
0
 /// <summary>
 /// Sets part number header.
 /// </summary>
 /// <param name="headers">The http request header.</param>
 /// <param name="value">The header value.</param>
 public static void SetPartNumber(this HttpRequestHeaders headers, int value)
 {
     if (value != 0)
     {
         headers.Add("x-bz-part-number", value.ToString());
     }
 }
Exemplo n.º 28
0
        public void Headers_Response()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            headers.Add("Age", "vv");
            Assert.AreEqual("vv", headers.GetValues("Age").First(), "#1");

            headers.Clear();
            headers.TryAddWithoutValidation("Age", "vv");
            Assert.AreEqual("vv", headers.GetValues("Age").First(), "#2");

            // .NET encloses the "Age: vv" with two whitespaces.
            var normalized = Regex.Replace(message.ToString(), @"\s", "");

#if !__WATCHOS__
            if (HttpClientTestHelpers.UsingSocketsHandler)
#endif
            Assert.AreEqual("Method:GET,RequestUri:'<null>',Version:2.0,Content:<null>,Headers:{Age:vv}", normalized, "#3");
#if !__WATCHOS__
            else
            {
                Assert.AreEqual("Method:GET,RequestUri:'<null>',Version:1.1,Content:<null>,Headers:{Age:vv}", normalized, "#3");
            }
#endif
        }
Exemplo n.º 29
0
        public static void AddIdempotencyHeader(this HttpRequestHeaders @this, string idempotencyToken)
        {
            @this.ThrowIfNull(typeof(HttpRequestHeaders).Name.ToLower());
            idempotencyToken.ThrowIfNullOrWhiteSpace(nameof(idempotencyToken));

            @this.Add(IdempotencyHeader, idempotencyToken);
        }
Exemplo n.º 30
0
        private void CopyHeaders(string prefix, IHeaderDictionary sourceHeaders, HttpRequestHeaders destinationHeaders)
        {
            foreach (var sourceHeader in sourceHeaders)
            {
                if (ShouldAddHeader(sourceHeader.Key) && !destinationHeaders.Contains(sourceHeader.Key))
                {
                    var sourceHeaderValues = sourceHeader.Value.First().Split(';');
                    var cookieValues       = new List <string>();
                    foreach (var sourceHeaderValue in sourceHeaderValues)
                    {
                        var sourceHeaderValueTrimmed = sourceHeaderValue.Trim();
                        if (ShouldAddCookie(prefix, sourceHeaderValueTrimmed))
                        {
                            var cookieKey   = GetCookieKey(prefix, sourceHeaderValueTrimmed);
                            var cookieValue = GetCookieValue(sourceHeaderValueTrimmed);

                            cookieValue = Uri.UnescapeDataString(cookieValue);

                            cookieValue = $"{cookieKey}={cookieValue}";
                            cookieValues.Add(cookieValue);
                        }
                    }

                    if (cookieValues.Any())
                    {
                        destinationHeaders.Add(HeaderNames.Cookie, cookieValues);
                    }
                }
            }
        }