/// <summary>
        /// Function that checks if user data inside the request headers are valid (authentication)
        /// </summary>
        /// <param name="user">requesting user</param>
        /// <param name="db">database</param>
        /// <param name="headers">header data</param>
        /// <param name="accessLevel">accesslevel required</param>
        /// <returns>
        /// Enum based on checks
        /// </returns>
        public static AuthorizatedMessage CheckIfAuthorized(ref User user, ref IDatabaseServiceProvider db, HttpRequestHeaders headers, AccessLevel accessLevel)
        {
            if (!headers.TryGetValues("username", out var usernameValues) || !headers.TryGetValues("token", out var tokenValues))
            {
                return(AuthorizatedMessage.NoUserError);
            }

            var username = usernameValues.FirstOrDefault();
            var token    = tokenValues.FirstOrDefault();

            user = db.Users.Where(x => x.Username == username && x.Token == token).FirstOrDefault();

            if (user == null)
            {
                return(AuthorizatedMessage.WrongCredentialsError);
            }

            if (user.IsActive == false)
            {
                return(AuthorizatedMessage.NotActiveError);
            }

            if ((int)accessLevel == 1 && user.AccessLevel != "Admin")
            {
                return(AuthorizatedMessage.AccessLevelError);
            }

            return(AuthorizatedMessage.Authorized);
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //如果Action带有AllowAnonymousAttribute,则不进行授权验证
            if (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any())
            {
                return;
            }

            HttpRequestHeaders Headers = actionContext.Request.Headers;

            if (Headers != null)
            {
                IEnumerable <string> users  = null;
                IEnumerable <string> tokens = null;
                if (Headers.TryGetValues("user", out users) && Headers.TryGetValues("token", out tokens))
                {
                    string key2 = key + users.ElementAt(0);
                    string key3 = GetMd5_32byteANSI(key2);
                    if (tokens.ElementAt(0) == key3)
                    {
                        verifyResult = true;
                    }
                    else
                    {
                        verifyResult = false;
                    }
                }
            }
            if (!verifyResult)
            {
                //如果验证不通过,则返回401错误,并且Body中写入错误原因
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Token 不正确");
            }
        }
Beispiel #3
0
        internal static PageInfo ResolvePageInfoHeaders(HttpRequestHeaders headers)
        {
            PageInfo             pageInfo = new PageInfo();
            IEnumerable <string> values   = Enumerable.Empty <string>();

            pageInfo.Page     = headers.TryGetValues(HeaderValues.KRYPTON_PAGE, out values) ? int.Parse(values.FirstOrDefault()) : pageInfo.Page;
            pageInfo.Total    = headers.TryGetValues(HeaderValues.KRYPTON_TOTAL, out values) ? int.Parse(values.FirstOrDefault()) : pageInfo.Total;
            pageInfo.PageSize = headers.TryGetValues(HeaderValues.KRYPTON_PAGE_SIZE, out values) ? int.Parse(values.FirstOrDefault()) : pageInfo.PageSize;
            return(pageInfo);
        }
Beispiel #4
0
        public void Test1()
        {
            object responseResult;

            IStudentService student = Lark.Core.Lark.Wrap <IStudentService>("http://localhost:6346");

            responseResult = student.QueryName(12, "upper", "234");
            System.Console.WriteLine(responseResult.ToString());
            WrapBase           wrap = (WrapBase)student;
            HttpRequestHeaders HttpRequestHeaders = wrap.MyHttpRequestMessagea.Headers;
            HttpContent        httpContent        = wrap.MyHttpRequestMessagea.Content;

            List <string>        values          = new List <string>();
            IEnumerable <string> valuesEnumrable = null;

            //appcode:just one
            Assert.IsTrue(HttpRequestHeaders.Contains("appcode") || httpContent.Headers.Contains("appcode"));
            bool l = HttpRequestHeaders.TryGetValues("appcode", out valuesEnumrable) ? true : httpContent.Headers.TryGetValues("appcode", out valuesEnumrable);

            values = valuesEnumrable.ToList();
            values.Sort();
            string valuestr = string.Join(",", values);

            Assert.IsTrue("appcode111111111111" == valuestr);


            //supportversion:3
            Assert.IsTrue(HttpRequestHeaders.Contains("supportversion") || httpContent.Headers.Contains("supportversion"));
            l      = HttpRequestHeaders.TryGetValues("supportversion", out valuesEnumrable) ? true : httpContent.Headers.TryGetValues("supportversion", out valuesEnumrable);
            values = valuesEnumrable.ToList();
            Assert.IsTrue(l && values.Count == 3);
            values.Sort();
            valuestr = string.Join(",", values);
            Assert.IsTrue("1.0,2.0,3.0" == valuestr);

            //case:2
            Assert.IsTrue(HttpRequestHeaders.Contains("case") || httpContent.Headers.Contains("case"));
            l      = HttpRequestHeaders.TryGetValues("case", out valuesEnumrable) ? true : httpContent.Headers.TryGetValues("case", out valuesEnumrable);
            values = valuesEnumrable.ToList();
            Assert.IsTrue(l && values.Count == 2);
            values.Sort();
            valuestr = string.Join(",", values);
            Assert.IsTrue("lower,upper" == valuestr);


            //prefix:1
            Assert.IsTrue(HttpRequestHeaders.Contains("prefix") || httpContent.Headers.Contains("prefix"));
            l      = HttpRequestHeaders.TryGetValues("prefix", out valuesEnumrable) ? true : httpContent.Headers.TryGetValues("prefix", out valuesEnumrable);
            values = valuesEnumrable.ToList();
            Assert.IsTrue(l && values.Count == 1);
            values.Sort();
            valuestr = string.Join(",", values);
            Assert.IsTrue("234" == valuestr);
        }
Beispiel #5
0
        private static string GetCookie(HttpRequestHeaders header, string headerName)
        {
            IEnumerable <string> cookies;

            if (header.TryGetValues("Cookie", out cookies))
            {
                return(giveMeAuth(cookies, headerName));
            }
            if (header.TryGetValues("header", out cookies))
            {
                return(giveMeAuth(cookies, headerName));
            }
            return(null);
        }
        /// <summary>
        /// 读取header标头,如果不存在,返回空字符串
        /// </summary>
        /// <param name="headers">The headers</param>
        /// <param name="key">The key</param>
        /// <returns>
        /// The String
        /// </returns>
        public static string Read(this HttpRequestHeaders headers, string key)
        {
            IEnumerable <string> values;

            headers.TryGetValues(key, out values);
            return(values == null ? string.Empty : values.FirstOrDefault() ?? string.Empty);
        }
Beispiel #7
0
        internal static string ResolveSortHeader(HttpRequestHeaders headers)
        {
            IEnumerable <string> values = Enumerable.Empty <string>();

            headers.TryGetValues(HeaderValues.KRYPTON_SORT, out values);
            return(values?.FirstOrDefault() ?? null);
        }
        public async Task User_Authorization_Is_Propagated()
        {
            // Arrange
            HttpRequestHeaders actualHeaders = null;
            var sut = new AddUserAuthorizationForTest
            {
                UnitTest_SendAsyncDependencyInjection = (req, cancellationToken) =>
                {
                    actualHeaders = req.Headers;
                    return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                }
            };

            const string userAuthorization = "eymannen";

            FulcrumApplication.Context.ValueProvider.SetValue(Constants.NexusUserAuthorizationKeyName, userAuthorization);

            // Act
            var request = new HttpRequestMessage(HttpMethod.Post, "http://example.com/");
            await sut.SendAsync(request);

            // Assert
            Assert.IsNotNull(actualHeaders);
            Assert.IsTrue(actualHeaders.TryGetValues(Constants.NexusUserAuthorizationHeaderName, out var header));
            Assert.AreEqual(userAuthorization, header.First());
        }
Beispiel #9
0
        /// <summary>
        ///		Retrieve the value of an optional HTTP request header.
        /// </summary>
        /// <param name="requestHeaders">
        ///		The HTTP request headers to examine.
        /// </param>
        /// <param name="headerName">
        ///		The name of the target header.
        /// </param>
        /// <returns>
        ///		The header value, or <c>null</c> if the header is not present (or an <see cref="string.Empty"/> string if the header is present but has no value).
        /// </returns>
        public static string GetOptionalHeaderValue(this HttpRequestHeaders requestHeaders, string headerName)
        {
            if (requestHeaders == null)
            {
                throw new ArgumentNullException(nameof(requestHeaders));
            }

            if (String.IsNullOrWhiteSpace(headerName))
            {
                throw new ArgumentException("Argument cannot be null, empty, or composed entirely of whitespace: 'headerName'.", nameof(headerName));
            }

            IEnumerable <string> headerValues;

            if (!requestHeaders.TryGetValues(headerName, out headerValues))
            {
                return(null);
            }

            return
                (headerValues.DefaultIfEmpty(
                     String.Empty
                     )
                 .FirstOrDefault());
        }
Beispiel #10
0
        /// <summary>
        /// This method extracts a token from the HttpRequestHeaders.
        /// </summary>
        /// <param name="headers">The headers of a HttpRequest.</param>
        /// <returns>Returns the token or null.</returns>
        public static void GetTokenFromHeader(HttpRequestHeaders headers, out string token)
        {
            IEnumerable <string> key;

            // If the headers contain the key "token".
            if (headers.TryGetValues("token", out key) != false)
            {
                headers.TryGetValues("token", out key);
                token = key.First <string>().Trim('"');
            }
            else
            {
                token = null;
            }
            return;
        }
Beispiel #11
0
        public static IEnumerable <string> FindValues(this HttpRequestHeaders headers, string name)
        {
            IEnumerable <string> apiKeys;

            headers.TryGetValues(name, out apiKeys);
            return(apiKeys ?? Enumerable.Empty <string>());
        }
Beispiel #12
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            HttpRequestHeaders   headers = actionContext.Request.Headers;
            IEnumerable <string> xsrfTokenList;

            if (actionContext.Request.Method == HttpMethod.Get || SkipFilterCheck(actionContext))
            {
                return;
            }

            if (!headers.TryGetValues(AppConstants.XsrfHeader, out xsrfTokenList))
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                return;
            }

            string      tokenHeaderValue = xsrfTokenList.First();
            CookieState tokenCookie      = actionContext.Request.Headers.GetCookies().Select(c => c[AppConstants.XsrfCookie]).FirstOrDefault();

            if (tokenCookie == null)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                return;
            }

            try
            {
                AntiForgery.Validate(tokenCookie.Value, tokenHeaderValue);
            }
            catch (HttpAntiForgeryException ex)
            {
                NLogLogger.Instance.Log(ex);
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
        }
        public override bool TryParse(out ArmorTokenHeader armorTokenHeader)
        {
            armorTokenHeader = new ArmorTokenHeader();
            IEnumerable <string> authHeaders;

            var hasAuthHeader = headers.TryGetValues("Authorization",
                                                     out authHeaders);

            if (!hasAuthHeader)
            {
                return(false);
            }

            var armorHeader =
                authHeaders.SingleOrDefault(header => header.StartsWith("ARMOR"));

            if (armorHeader == null)
            {
                return(false);
            }

            armorTokenHeader.IsValid    = true;
            armorTokenHeader.ArmorToken = armorHeader.Replace("ARMOR ",
                                                              string.Empty);

            return(true);
        }
Beispiel #14
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            HttpRequestHeaders   headers = actionContext.Request.Headers;
            IEnumerable <string> xsrfTokenList;

            if (!headers.TryGetValues(XsrfHeader, out xsrfTokenList))
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                return;
            }

            string tokenHeaderValue = xsrfTokenList.First();



            //CookieState tokenCookie = actionContext.Request.Headers.GetCookies()
            //    .Select(x => x.Cookies.FirstOrDefault(y => y.Name == "XsrfCookie")).FirstOrDefault();

            var tokenCookie = actionContext.Request.Headers.GetCookies().FirstOrDefault()?[XsrfCookie];

            if (tokenCookie == null)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                return;
            }

            try
            {
                AntiForgery.Validate(tokenCookie.Value, tokenHeaderValue);
            }
            catch (HttpAntiForgeryException)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
        }
        public bool IsDateValid(HttpRequestHeaders headers)
        {
            DateTime             utcNow = DateTime.UtcNow;
            DateTime             date;
            IEnumerable <string> dateStrings;

            if (headers.TryGetValues(AbsDateHeader, out dateStrings))
            {
                var dateString = dateStrings.FirstOrDefault();
                if (!DateTime.TryParseExact(dateString, "r", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date))
                {
                    return(false);
                }
            }
            else
            {
                if (headers.Date.HasValue)
                {
                    date = headers.Date.Value.UtcDateTime;
                }
                else
                {
                    return(false);
                }
            }
            return(date >= utcNow.AddMinutes(-ValidityPeriodInMinutes) && date <= utcNow.AddMinutes(ValidityPeriodInMinutes));
        }
Beispiel #16
0
        private void ParseHeaders(HttpRequestHeaders headers)
        {
            IEnumerable <string>  vals;
            Func <string, string> parseHeader = (k) =>
            {
                if (headers.TryGetValues(k, out vals))
                {
                    return(vals.First());
                }
                return(null);
            };

            foreach (string key in RequiredHeaders)
            {
                payloadArgs[key] = parseHeader(key);
            }
            payloadArgs[Constants.XHubSignature] = parseHeader(Constants.XHubSignature);

            var missingRequiredArgs = payloadArgs.Where(kvp => RequiredHeaders.Contains(kvp.Key) && string.IsNullOrWhiteSpace(kvp.Value));

            if (missingRequiredArgs.Any())
            {
                ThrowMissingParameter(missingRequiredArgs.Select(ma => ma.Key));
            }
        }
        private string ExtractTokenValue(HttpRequestHeaders headers)
        {
            IEnumerable <string> tokenValues;

            headers.TryGetValues("authToken", out tokenValues);
            return(tokenValues == null ? null : tokenValues.SingleOrDefault());
        }
Beispiel #18
0
        public ValueProviderResult GetValue(string key)
        {
            IEnumerable <string> values;

            return(_headers.TryGetValues(XHeaderPrefix + key, out values)
                ? new ValueProviderResult(values.First(), values.First(), CultureInfo.CurrentCulture)
                : null);
        }
        private string GetHeader(HttpRequestHeaders headers, string name)
        {
            if (headers.TryGetValues(name, out var values))
            {
                return(values.First());
            }

            return(null);
        }
Beispiel #20
0
        private static bool IsHeaderSet(HttpRequestHeaders headers, string name, params string[] expectedValues)
        {
            if (!headers.TryGetValues(name, out var actualValues))
            {
                return(false);
            }

            return(actualValues.SequenceEqual(expectedValues));
        }
 public static SiteSettingViewModel GetSiteSettingViewModel(this HttpRequestHeaders httpHeaders)
 {
     if (httpHeaders.TryGetValues("litium-request-context", out var items))
     {
         var json    = items.First();
         var jObject = JObject.Parse(json);
         return(jObject.ToObject <SiteSettingViewModel>());
     }
     return(null);
 }
Beispiel #22
0
        public static async Task <bool> ValidateRequest(HttpRequestHeaders requestHeaders, string requestBody, TraceWriter log)
        {
            requestHeaders.TryGetValues("SignatureCertChainUrl", out var signatureChainUrls);
            var signatureChainUrl = signatureChainUrls == null ? null : signatureChainUrls.FirstOrDefault();

            if (String.IsNullOrWhiteSpace(signatureChainUrl))
            {
                return(false);
            }

            Uri certUrl;

            try
            {
                certUrl = new Uri(signatureChainUrl);
            }
            catch
            {
                return(false);
            }

            requestHeaders.TryGetValues("Signature", out var signatures);

            var signature = signatures == null ? null : signatures.FirstOrDefault();

            if (String.IsNullOrWhiteSpace(signature))
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(requestBody))
            {
                return(false);
            }
            var valid = await AlexaRequestSecurity.Verify(signature, certUrl, requestBody, log);

            if (!valid)
            {
                return(false);
            }

            return(true);
        }
Beispiel #23
0
        internal static JObject ResolveFilterInfoHeader(HttpRequestHeaders headers)
        {
            IEnumerable <string> values = Enumerable.Empty <string>();

            if (!headers.TryGetValues(HeaderValues.KRYPTON_FILTER_INFO, out values))
            {
                return(null);
            }
            return(JsonConvert.DeserializeObject <JObject>(values.FirstOrDefault()));
        }
 private bool TryGetHeaderValue(HttpRequestHeaders headers, string name, out string value)
 {
     if (headers.TryGetValues(name, out IEnumerable <string> values) && values.Any())
     {
         value = values.First();
         return(true);
     }
     value = null;
     return(false);
 }
Beispiel #25
0
        public static bool TryGetHeaderValue(this HttpRequestHeaders n, string key, out string header)
        {
            if (n.TryGetValues(key, out var vs))
            {
                header = vs.First();
                return(true);
            }

            header = null;
            return(false);
        }
Beispiel #26
0
        protected string GetHeaderValue(HttpRequestHeaders headers, string key)
        {
            IEnumerable <string> values;

            if (headers.TryGetValues(key, out values))
            {
                return(values.FirstOrDefault());
            }

            return(null);
        }
        private static string GetFirstOrNull(this HttpRequestHeaders headers, string key)
        {
            IEnumerable <string> values;

            if (headers.TryGetValues(key, out values))
            {
                return(values.FirstOrDefault());
            }

            return(null);
        }
        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="requestheaders"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private string GetValue(HttpRequestHeaders requestheaders, string name)
        {
            IEnumerable <string> values;

            if (requestheaders.TryGetValues(name, out values))
            {
                return(values.First());
            }

            return("");
        }
        public static string GetHeaderValue(this HttpRequestHeaders headers, string name)
        {
            IEnumerable <string> values;

            if (headers.TryGetValues(name, out values))
            {
                return(values.FirstOrDefault());
            }

            return(null);
        }
        public static bool CompareValue(this HttpRequestHeaders headers, string key, string value)
        {
            var result = false;

            if (headers.TryGetValues(key, out IEnumerable <string> results))
            {
                var first = results.FirstOrDefault();
                result = first != null?first.Equals(value) : false;
            }

            return(result);
        }