Ejemplo n.º 1
0
        public static string BuildPaging <T>(StringValues limit, StringValues offset)
        {
            if (limit.Count < 1)
            {
                return(null);
            }

            var sb       = new StringBuilder();
            var hasLimit = int.TryParse(limit.First(), out int limitValue);

            if (hasLimit == true)
            {
                sb.Append($" count='{limit.First()}'");
            }

            if (offset.Count > 0)
            {
                var hasOffSet = int.TryParse(offset.First(), out int offsetValue);

                if (hasOffSet == true && hasLimit == true)
                {
                    sb.Append($" page='{offsetValue / limitValue + 1}'");
                }
            }

            return(sb.ToString());
        }
Ejemplo n.º 2
0
        public static async Task <ClaimsPrincipal> ValidateTokenAsync(StringValues values)
        {
            var scheme = values.First().Split(' ').First();
            var value  = values.First().Split(' ').Last();

            if (scheme != "Bearer")
            {
                return(null);
            }

            var config = await _configurationManager.GetConfigurationAsync(CancellationToken.None);

            var issuer   = Environment.GetEnvironmentVariable("ISSUER");
            var audience = Environment.GetEnvironmentVariable("AUDIENCE");

            var validationParameter = new TokenValidationParameters()
            {
                RequireSignedTokens      = true,
                ValidAudience            = audience,
                ValidateAudience         = true,
                ValidIssuer              = issuer,
                ValidateIssuer           = true,
                ValidateIssuerSigningKey = true,
                ValidateLifetime         = true,
                IssuerSigningKeys        = config.SigningKeys
            };

            ClaimsPrincipal result = null;
            var             tries  = 0;

            while (result == null && tries <= 1)
            {
                try
                {
                    var handler = new JwtSecurityTokenHandler();
                    result = handler.ValidateToken(value, validationParameter, out var token);
                }
                catch (SecurityTokenSignatureKeyNotFoundException)
                {
                    // This exception is thrown if the signature key of the JWT could not be found.
                    // This could be the case when the issuer changed its signing keys, so we trigger a
                    // refresh and retry validation.
                    _configurationManager.RequestRefresh();
                    tries++;
                }
                catch (SecurityTokenException)
                {
                    return(null);
                }
            }

            return(result);
        }
Ejemplo n.º 3
0
        // private
        static private DbUtils.QueryMap ParseQueryParameters(LoginResponse login, String serviceName, IQueryCollection queryParameters)
        {
            CrudService service = RequestFilter.GetService(login, serviceName);

            DbUtils.QueryMap queryFields   = DbUtils.QueryMap.Create();
            JObject          serviceFields = JObject.Parse(service.Fields);

            foreach (var item in serviceFields)
            {
                JToken field = item.Value;

                if (field.Value <Boolean> ("primaryKey") == true)
                {
                    StringValues values = queryParameters [item.Key];

                    if (values.Count > 0)
                    {
                        String type = field.Value <String> ("type");

                        if (type == null || type.Equals("s"))
                        {
                            queryFields.Add(item.Key, values.First());
                        }
                        else if (type.Equals("n") || type.Equals("i"))
                        {
                            queryFields.Add(item.Key, int.Parse(values.First()));
                        }
                        else if (type.Equals("b"))
                        {
                            queryFields.Add(item.Key, Boolean.Parse(values.First()));
                        }
                    }
                }
            }
            // se não for admin, limita os resultados para as crudGroup vinculadas a empresa do usuário
            int?crudGroupOwner = login.user.CrudGroupOwner;

            if (crudGroupOwner != 1)
            {
                if (serviceFields.ContainsKey("crudGroupOwner"))
                {
                    queryFields["crudGroupOwner"] = crudGroupOwner;
                }
                else if (serviceFields.ContainsKey("crudGroup"))
                {
                    queryFields["crudGroup"] = login.groups;
                }
            }

            return(queryFields);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Obtiene el valor de la cabecera Authorization, retorna sólo la cadena con el token en formato Json Web Token (JWT) sin el tipo de autorización. Retorna "" en caso de que no exista la cabecera.
        /// </summary>
        /// <param name="httpContext">Objeto de la clase HttpContext</param>
        /// <returns></returns>
        public static string GetTokenFromHeader(HttpContext httpContext)
        {
            string       header       = null;
            StringValues headerValues = new StringValues();

            if (httpContext.Request.Headers.TryGetValue("Authorization", out headerValues))
            {
                header = headerValues.First();
            }

            if (header == null)
            {
                return("");
            }

            var arrHeader = header.Split(' ');

            if (arrHeader.Length != 2)
            {
                return("");
            }

            if (arrHeader[1] == "null" || arrHeader[1] == "undefined")
            {
                return("");
            }

            return(arrHeader[1]);
        }
Ejemplo n.º 5
0
        public async Task <Dictionary <string, string> > GetClaims()
        {
            var token = new StringValues();

            // get bearer token of current request
            if (!Request.Headers.TryGetValue("Authorization", out token))
            {
                return(null);
            }

            // the token
            var bearerToken = token.First().Replace("Bearer ", "");

            try
            {
                // create a http GET request and set authorization header
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                var proxyPort = Environment.GetEnvironmentVariable("Api__ProxyPort");
                var result    = await httpClient.GetStringAsync($"http://localhost:{proxyPort}/me");

                return(JsonConvert.DeserializeObject <Dictionary <string, string> >(result));
            }
            catch (Exception e)
            {
                throw;
            }
        }
Ejemplo n.º 6
0
        public static string BuildFilter(Type modelType, StringValues filterValues)
        {
            var attributes = (Dictionary <string, string>)modelType.GetField("Fields").GetValue(null);

            if (filterValues.Count > 0)
            {
                var filter = filterValues.First();

                string   logicalOperator;
                string[] pieces;

                if (filter.Contains(" OR "))
                {
                    logicalOperator = "or";
                    pieces          = filter.Split(" OR ");
                }
                else
                {
                    logicalOperator = "and";
                    pieces          = filter.Split(" AND ");
                }

                var conditions = pieces.Select(x => ParseFilter(modelType, x, attributes));

                return($@"<filter type='{logicalOperator}'>
                    {string.Join("", conditions)}
                </filter>");
            }

            return(null);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Action filter method for UserUidParserAttribute
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            try
            {
                StringValues headerValues = new StringValues();
                string       userIdString = null;

                //UserType userType;

                var jwt = new TPaaSJWT(actionContext.HttpContext.Request.Headers["X-JWT-Assertion"].ToString());
                //Enum.TryParse(jwt.UserType, out userType);
                if (jwt != null && jwt.IsApplicationUserToken)
                {
                    userIdString = jwt.UserUid.ToString();
                }

                else if (actionContext.HttpContext.Request.Headers.TryGetValue("X-VisionLink-UserUid", out headerValues))
                {
                    userIdString = headerValues.First();
                }

                actionContext.HttpContext.Request.Headers.Add("UserUID_IdentityAPI", userIdString);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 8
0
        private static JToken GetValue(StringValues strValues)
        {
            if (strValues.Count() == 1)
            {
                return(new JValue(strValues.First()));
            }

            return(new JArray(strValues));
        }
        public static string GetCommonId(this Controller controller)
        {
            var str = new StringValues();

            if (!controller.Request.Headers.TryGetValue("CommonId", out str))
            {
                return(null);
            }

            return(str.First());
        }
Ejemplo n.º 10
0
        public static void Forward(HttpRequest request, IForwardingClient client, string headerName, string headerForwardedName, string prependedText = "")
        {
            StringValues authToken = StringValues.Empty;

            request.Headers.TryGetValue(headerName, out authToken);

            if (authToken.Any())
            {
                client.ForwardHeader(headerForwardedName, $"{prependedText}{authToken.First()}").Wait();
            }
        }
Ejemplo n.º 11
0
Archivo: Utils.cs Proyecto: Sdzeng/Kard
        /// <summary>
        /// 获取客户端ip
        /// </summary>
        /// <param name="context"></param>
        /// <param name="real"></param>
        /// <returns></returns>
        public static string GetClientIP(HttpContext context, bool real = true)
        {
            var          result  = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
            var          headers = context.Request.Headers;
            StringValues sVals   = string.Empty;

            if (headers.TryGetValue("X-Psc-Client-IP", out sVals) && ValidateIPAddress(sVals.First()))
            {
                result = sVals.First();
            }
            else if (headers.TryGetValue("X-OPW-Real-IP", out sVals) && ValidateIPAddress(sVals.First()))
            {
                result = sVals.First();
            }
            if (!real)
            {
                if (headers.TryGetValue("X-Forwarded-For", out sVals) && ValidateIPAddress(sVals.First()))
                {
                    result = sVals.First();
                }
                else if (headers.TryGetValue("X-Surfcache-For", out sVals) && ValidateIPAddress(sVals.First()))
                {
                    result = sVals.First();
                }
                else if (headers.TryGetValue("X-Real-IP", out sVals) && ValidateIPAddress(sVals.First()))
                {
                    result = sVals.First();
                }
                else if (headers.TryGetValue("Client-IP", out sVals) && ValidateIPAddress(sVals.First()))
                {
                    result = sVals.First();
                }
            }
            return(result);
        }
        public static IQueryable <T> ApplyFilter <T>(IQueryable <T> modelQuery, StringValues filterValues)
        {
            Type modelType = typeof(T);

            var query = modelQuery;

            if (filterValues.Count > 0)
            {
                var filter = filterValues.First();

                string logicalOperator = null;
                string left            = null;
                string right           = null;

                if (filter.Contains(" AND "))
                {
                    logicalOperator = "AND";
                    var pieces = filter.Split(" AND ");
                    left  = pieces[0];
                    right = pieces[1];
                }
                else if (filter.Contains(" OR "))
                {
                    logicalOperator = "OR";
                    var pieces = filter.Split(" OR ");
                    left  = pieces[0];
                    right = pieces[1];
                }
                else
                {
                    left = filter;
                }

                if (logicalOperator == null)
                {
                    return(query.Where(TranslateFilter <T>(left)).AsQueryable <T>());
                }

                var leftQuery  = query.Where(TranslateFilter <T>(left)).AsQueryable <T>();
                var rightQuery = query.Where(TranslateFilter <T>(right)).AsQueryable <T>();

                if (logicalOperator == "AND")
                {
                    return(leftQuery.Intersect(rightQuery));
                }
                else
                {
                    return(leftQuery.Union(rightQuery));
                }
            }
            return(query);
        }
        private JToken CreateJToken(StringValues values)
        {
            switch (values.Count)
            {
            case 0:
                return(JToken.Parse("''"));

            case 1:
                var value = values.First().Replace("'", @"\'");
                return(JToken.Parse($"'{value}'"));

            default:
                return(JToken.Parse($"['{string.Join("','", values.ToArray())}']"));
            }
        }
        public static IQueryable <T> ApplySort <T>(IQueryable <T> modelQuery, StringValues dataFields, StringValues orderBy)
        {
            if (dataFields.Count < 1)
            {
                return(modelQuery);
            }

            var dataField = dataFields.First();

            if (orderBy.Count < 1 || orderBy.First().ToLower() == "asc")
            {
                return(modelQuery.OrderBy(TranslateSort <T, Object>(dataField)).AsQueryable());
            }

            return(modelQuery.OrderByDescending(TranslateSort <T, Object>(dataField)).AsQueryable());
        }
Ejemplo n.º 15
0
        private static void ProcessContinuationToken(Dictionary <string, string> headers, StringValues continuationTokens)
        {
            if (continuationTokens.Count == 0)
            {
                return;
            }

            if (continuationTokens.Count > 1)
            {
                throw new InvalidArgumentException(
                          new InternalRestError(
                              ErrorConstants.ToManyContinuationTokensErrorCode,
                              ErrorConstants.ToManyContinuationTokensErrorMessage));
            }

            headers.Add(HeaderConstants.ContinuationToken, continuationTokens.First());
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!_authOptions.AuthHeaderCheckEnabled)
            {
                return;
            }

            StringValues values = new StringValues();

            if (context.HttpContext.Request.Headers.TryGetValue("authorization_mobile", out values))
            {
                if (!values.Any())
                {
                    context.Result = new UnauthorizedObjectResult("Missing or invalid token");
                }
                else
                {
                    var    token = values.First();
                    string mobileTokenDecrypted;

                    try
                    {
                        mobileTokenDecrypted = ConfigEncryptionHelper.UnprotectString(_mobileTokenEncrypted);
                    }
                    catch (Exception e)
                    {
                        _logger.LogError($"Configuration error. Cannot decrypt the mobileToken from configuration. MobileTokenEncrypted: {_mobileTokenEncrypted}. Message: {e.Message}");
                        throw;
                    }

                    if (!token.Equals(mobileTokenDecrypted) || string.IsNullOrEmpty(mobileTokenDecrypted))
                    {
                        context.Result = new UnauthorizedObjectResult("Missing or invalid token");
                    }
                    else
                    {
                        return;
                    }
                }
            }
            else
            {
                context.Result = new UnauthorizedObjectResult("Missing or invalid token");
            }
        }
        private static string GetGitHubEventName(HttpRequest request)
        {
            StringValues header = request.Headers[GitHubConstants.EventHeader];

            if (header == StringValues.Empty)
            {
                throw new GitHubWebhookException($"Missing {GitHubConstants.EventHeader} header");
            }

            string eventName = header.First();

            if (string.IsNullOrWhiteSpace(eventName))
            {
                throw new GitHubWebhookException($"Null, empty or whitespace event name in {GitHubConstants.EventHeader} header");
            }

            return(eventName);
        }
Ejemplo n.º 18
0
        private string GetAccessToken()
        {
            var authorizationHeaders = httpContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationToken);

            if (authorizationHeaders)
            {
                var header = authorizationToken.First().Trim();
                if (header.StartsWith("Bearer"))
                {
                    var value = header.Substring("Bearer".Length).Trim();
                    if (value != null && value.Length > 0)
                    {
                        return(value);
                    }
                }
            }
            return(string.Empty);
        }
Ejemplo n.º 19
0
        public static string GetIpAddress(this HttpRequest request)
        {
            var          emptyValues = default(StringValues);
            StringValues header      = request.Headers.FirstOrDefault(h => h.Key == "CF-Connecting-IP").Value;

            if (header == emptyValues)
            {
                header = request.Headers.FirstOrDefault(h => h.Key == "X-Forwarded-For").Value;
            }
            if (header != emptyValues)
            {
                return(header.First());
            }
            else
            {
                return(request.HttpContext.Connection.RemoteIpAddress.ToString());
            }
        }
Ejemplo n.º 20
0
        public static QueryParameters GetQuery(this HttpRequest request)
        {
            QueryParameters result = new QueryParameters();

            StringValues skip = request.Query["$skip"];
            StringValues top  = request.Query["$top"];

            if (skip.Count > 0)
            {
                result.Skip = int.Parse(skip.First());
            }

            if (top.Count > 0)
            {
                result.Top = int.Parse(top.First());
            }

            return(result);
        }
Ejemplo n.º 21
0
        public static string FormatStringValues(StringValues values)
        {
            if (StringValues.IsNullOrEmpty(values))
            {
                return(string.Empty);
            }

            if (values.Count == 0)
            {
                return(QuoteIfNeeded(values[0]));
            }

            if (values.Count == 1)
            {
                return(values.First());
            }

            return(string.Join(",", values.Select(QuoteIfNeeded)));
        }
        private static string GetGitHubEventSignature(HttpRequest request)
        {
            StringValues header = request.Headers[GitHubConstants.SignatureHeader];

            if (header == StringValues.Empty)
            {
                throw new GitHubWebhookException($"Missing {GitHubConstants.SignatureHeader} header");
            }

            string signature = header.First();

            if (string.IsNullOrWhiteSpace(signature))
            {
                throw new GitHubWebhookException($"Null, empty or whitespace signature in {GitHubConstants.SignatureHeader} header");
            }

            if (!signature.StartsWith("sha1="))
            {
                throw new GitHubWebhookException("Unexpected signature type (expected SHA1)");
            }

            return(signature.Substring("sha1=".Length));
        }
Ejemplo n.º 23
0
        private Guid?ExtractApiKey()
        {
            const string iotApiKeyParameterName = "IoTApiKey";

            if (!Request.Headers.ContainsKey(iotApiKeyParameterName))
            {
                return(null);
            }

            StringValues values = HttpContext.Request.Headers[iotApiKeyParameterName];

            if (values.Count != 1)
            {
                return(null);
            }

            if (Guid.TryParse(values.First(), out var result))
            {
                return(result);
            }

            return(null);
        }
Ejemplo n.º 24
0
        public JwtContextAuthenticatorPipe(String secret) : base(o =>
        {
            if (o == null)
            {
                throw new ArgumentNullException(nameof(o));
            }

            // validate inputs
            IHeaderDictionary headers = o.Request?.Headers;
            if (null == headers)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            // check for authorization header
            String headerKeyAuth = HttpRequestHeader.Authorization.ToString();
            if (!headers.ContainsKey(headerKeyAuth))
            {
                throw new ArgumentNullException(nameof(headerKeyAuth));
            }

            // get header and validate content
            StringValues values = headers[headerKeyAuth];

            if (!values.Count.Equals(1))
            {
                throw new ArgumentOutOfRangeException(nameof(values));
            }

            String value = values.First().Trim();

            if (!value.StartsWith(BEARER_PREFIX))
            {
                throw new FormatException("unknown schema");
            }

            // extract token
            String token = value.Substring(BEARER_PREFIX.Length).Trim();

            if (String.IsNullOrWhiteSpace(token))
            {
                throw new FormatException("empty token");
            }

            // prepare to decode token

            IJsonSerializer serializer   = new JsonNetSerializer();
            IDateTimeProvider provider   = new UtcDateTimeProvider();
            IJwtValidator validator      = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder decoder          = new JwtDecoder(serializer, validator, urlEncoder);

            // decode token
            String json = decoder.Decode(token, secret, true);

            if (String.IsNullOrWhiteSpace(json))
            {
                throw new FormatException("decoded json empty");
            }

            // deserialize json
            JwtPayload payload = serializer.Deserialize <JwtPayload>(json);

            // validate
            if (null == payload)
            {
                throw new FormatException("unknown payload schema");
            }

            if (DateTime.Now > payload.Exp || DateTime.Now < payload.Iat)
            {
                throw new TokenExpiredException("token expired");
            }

            return(payload);
        }) { }