internal static string CanonicalizedHeaders(HttpRequestHeaders headers)
        {
            var canonicalizedString = new CanonicalizedString(string.Empty);

            var keyList =
                headers.Where(h => h.Key.StartsWith("x-ms-", StringComparison.OrdinalIgnoreCase)).Select(header => header.Key).ToList();

            keyList.Sort();
            foreach (string str2 in keyList)
            {
                var    builder = new StringBuilder(str2);
                string str3    = ":";
                foreach (string str4 in GetHeaderValues(headers, str2))
                {
                    string str5 = str4.Replace("\r\n", string.Empty);
                    builder.Append(str3);
                    builder.Append(str5);
                    str3 = ",";
                }

                canonicalizedString.AppendCanonicalizedElement(builder.ToString());
            }

            return(canonicalizedString.Value.TrimEnd('\n').TrimStart('\n'));
        }
Exemplo n.º 2
0
 /// <summary>
 /// Extracts all headers provided. Does a case-insensitive selection.
 /// </summary>
 /// <param name="headers">this parameter</param>
 /// <param name="headerNames">Name of the headers</param>
 /// <returns></returns>
 public static IEnumerable <KeyValuePair <string, IEnumerable <string> > > ExtractHeadersValues(
     this HttpRequestHeaders headers,
     params string[] headerNames)
 {
     return(headers.Where(x =>
                          headerNames.Any(h => h.Equals(x.Key, StringComparison.CurrentCultureIgnoreCase))));
 }
Exemplo n.º 3
0
        internal static Dictionary <string, object> GetHeadersValues(HttpRequestHeaders headers)
        {
            var dic = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            foreach (var header in headers.Where(pair => pair.Key.StartsWith(CustomHeaderPrefix, StringComparison.OrdinalIgnoreCase)))
            {
                var key = header.Key.Substring(CustomHeaderPrefix.Length).Replace("-", string.Empty);
                dic[key] = header.Value;
            }
            return(dic);
        }
Exemplo n.º 4
0
        private static IEnumerable <string> GetHeaderValues(HttpRequestHeaders headers, string headerName)
        {
            var header = headers.Where(
                fx => fx.Key.Equals(headerName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (header.Key != null && header.Value != null)
            {
                return(header.Value);
            }

            return(new List <string>());
        }
Exemplo n.º 5
0
        public static uint GetVersionRequestHeader(this HttpRequestHeaders headers)
        {
            var version = headers.Where(header =>
                                        header.Key.Equals(VersionHeader, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            ValidateHeader(version, CartException.InvalidVersionHeader());

            uint parsed = 0;

            if (UInt32.TryParse(version.Value.FirstOrDefault(), out parsed))
            {
                return(parsed);
            }

            throw new ArgumentException("could not parse version");
        }
Exemplo n.º 6
0
        public static string GetAuthorizationHeader(this HttpRequestHeaders headers)
        {
            var authHeader = headers.Where(header =>
                                           header.Key.Equals(Authorization, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            var exception = CartException.InvalidAuthorizationHeader();

            ValidateHeader(authHeader, exception);

            var headerValue = authHeader.Value.FirstOrDefault().Split(' ');

            if (headerValue.Count() != 2 ||
                !headerValue[0].Equals(AuthenticationHeader, StringComparison.OrdinalIgnoreCase))
            {
                throw exception;
            }

            return(headerValue[1]);
        }
Exemplo n.º 7
0
        private async Task <CacheKey> GetKey(Type resultType, Uri uri, IEnumerable <string> defaultVaryByHeaders, HttpRequestHeaders headers)
        {
            var parts = new List <string>
            {
                typeof(HttpResponseMessage).IsAssignableFrom(resultType) ? "Http" : "Typed",
                uri?.ToString() ?? string.Empty
            };

            if (typeof(HttpResponseMessage).IsAssignableFrom(resultType))
            {
                var varyBy = await GetVaryByHeaders(uri, defaultVaryByHeaders);

                parts.AddRange(headers.Where(h => varyBy.Any(v => v.Equals(h.Key, StringComparison.OrdinalIgnoreCase)))
                               .SelectMany(h => h.Value.Select(v => $"{UriHelpers.NormalizeHeader(h.Key)}:{UriHelpers.NormalizeHeader(v)}"))
                               .Distinct());
            }

            return(new CacheKey(string.Join("-", parts)));
        }
        private DaikinUniversityApiSignature GenerateRequestAPISessionSignature(HttpMethod method, string apiRelativeUrl, HttpRequestHeaders headers)
        {
            StringBuilder sbToSign = new StringBuilder();

            // Get all the x-csod headers that we must include in signature except the signature itself
            var csodHeaders = headers.Where(w => w.Key.StartsWith("x-csod-") &&
                                            w.Key != "x-csod-signature")
                              .Select(sm => new
            {
                Key   = sm.Key,
                Value = sm.Value.Aggregate(string.Empty, (a, l) => a.Trim() + l.Trim())
            })
                              .Distinct()
                              .OrderBy(o => o.Key);

            sbToSign.Append(method);

            foreach (var csodHeader in csodHeaders)
            {
                sbToSign.AppendFormat("\n{0}:{1}", csodHeader.Key, csodHeader.Value);
            }

            sbToSign.Append("\n").Append(apiRelativeUrl);

            var signature = new DaikinUniversityApiSignature()
            {
                ApiSecret          = SessionToken != null ? SessionToken.Secret : ConfigApiSecret,
                RequestedSignature = sbToSign.ToString()
            };

            byte[] secretKeyBytes = Convert.FromBase64String(signature.ApiSecret);
            byte[] inputBytes     = Encoding.UTF8.GetBytes(sbToSign.ToString());

            using (var hmac = new HMACSHA512(secretKeyBytes))
            {
                byte[] hashValue = hmac.ComputeHash(inputBytes);

                signature.Signature = Convert.ToBase64String(hashValue);
            }

            return(signature);
        }
Exemplo n.º 9
0
        private IEnumerable <string> GetCanonicalParts(HttpRequestMessage request)
        {
            HttpRequestHeaders httpRequestHeaders = request.Headers;
            HttpContentHeaders httpContentHeaders = request.Content != null ? request.Content.Headers : null;

            yield return(request.Method.Method);

            yield return(httpContentHeaders != null && httpContentHeaders.ContentMD5 != null?Convert.ToBase64String(httpContentHeaders.ContentMD5) : string.Empty);

            yield return(httpContentHeaders != null && httpContentHeaders.ContentType != null ? httpContentHeaders.ContentType.MediaType : string.Empty);

            yield return(httpRequestHeaders.Date.HasValue ? httpRequestHeaders.Date.Value.ToString("r", CultureInfo.InvariantCulture) : string.Empty);

            IOrderedEnumerable <KeyValuePair <string, string> > customValues = httpRequestHeaders
                                                                               .Where(x => x.Key.StartsWith("X-ABS", StringComparison.InvariantCultureIgnoreCase))
                                                                               .Select(x => new KeyValuePair <string, string>(x.Key.ToLowerInvariant().Trim(), string.Join(",", x.Value.Select(v => v.Trim()))))
                                                                               .OrderBy(x => x.Key);

            foreach (var customValue in customValues)
            {
                yield return(string.Format("{0}:{1}", customValue.Key, customValue.Value));
            }
            yield return(request.RequestUri.PathAndQuery);
        }
Exemplo n.º 10
0
 public static string ActionId(this HttpRequestHeaders headers)
 {
     return(headers.Where(h => h.Key == ActionIdName).Select(h => h.Value).FirstOrDefault().FirstOrDefault());
 }
 private static Dictionary <string, StringValues> CopyWithoutContentHeaders(HttpRequestHeaders sourceHeaders)
 {
     return(sourceHeaders.Where(h => !h.Key.ToLowerInvariant().StartsWith("content-"))
            .ToDictionary(v => v.Key, v => new StringValues(v.Value.ToArray())));
 }
Exemplo n.º 12
0
        public async Task AuthenticateAsync(HttpAuthenticationContext httpAuthenticationContext, CancellationToken cancellationToken)
        {
            HttpRequestMessage httpRequestMessage = httpAuthenticationContext.Request;

            AuthenticationHeaderValue authenticationHeaderValue = httpRequestMessage.Headers.Authorization;

            HttpRequestHeaders headers = httpRequestMessage.Headers;

            try
            {
                if (headers.Where(x => x.Key == "AppKey" || x.Key == "appkey").Count() != 1)
                {
                    SetHttpUnauthorized(httpAuthenticationContext);
                    return;
                }

                if (headers.Where(x => x.Key == "AppToken" || x.Key == "apptoken").Count() != 1)
                {
                    SetHttpUnauthorized(httpAuthenticationContext);
                    return;
                }


                string appKey   = headers.GetValues("AppKey").FirstOrDefault();
                string appToken = headers.GetValues("AppToken").FirstOrDefault();

                if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appToken))
                {
                    appKey   = headers.GetValues("appkey").FirstOrDefault();
                    appToken = headers.GetValues("apptoken").FirstOrDefault();
                    if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appToken))
                    {
                        SetHttpUnauthorized(httpAuthenticationContext);
                        return;
                    }
                }

                IMDEndec iMDEndec = new IMDEndec();

                IMDResponse <string> resAppKey = iMDEndec.BDecrypt(appKey, "M3dit0cAppKeyV4l", "MeditocK");
                if (resAppKey.Code != 0)
                {
                    SetHttpUnauthorized(httpAuthenticationContext);
                    return;
                }

                IMDResponse <string> resAppToken = iMDEndec.BDecrypt(appToken, "M3dit0cAppToken8", "MeditocT");
                if (resAppKey.Code != 0)
                {
                    SetHttpUnauthorized(httpAuthenticationContext);
                    return;
                }

                if (resAppKey.Result != "MeditocAppKeyAuthenti0WebOK")
                {
                    SetHttpUnauthorized(httpAuthenticationContext);
                    return;
                }

                if (resAppToken.Result != "IMD.Meditoc.CallCenterSTthenticacion2020WebOK")
                {
                    SetHttpUnauthorized(httpAuthenticationContext);
                    return;
                }
            }
            catch (Exception)
            {
                SetHttpUnauthorized(httpAuthenticationContext);
                return;
            }

            GenericIdentity identity = new GenericIdentity("Meditoc");

            string[]         rol       = { "Manager" };
            GenericPrincipal principal = new GenericPrincipal(identity, rol);

            httpAuthenticationContext.Principal = principal;
        }