Beispiel #1
0
        public async Task <LoginResponse> Login([FromBody] LoginRequest request)
        {
            if (request == null)
            {
                var response = new LoginResponse();
                response.SetError("Invalid login request");
                return(response);
            }

            var res = await _accountServiceClient.User_TryLogin(new TryLoginRequest()
            {
                UserName = request.UserName,
                Password = request.Password,
                IP       = _ipAddressParser.GetClientIp(HttpContext).ToString()
            });

            if (res.HasError)
            {
                var response = new LoginResponse();
                //response.SetError("Invalid login/password");
                response.SetError(res.Message);

                HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                return(response);
            }

            if (res.Data == null)
            {
                var response = new LoginResponse();
                response.SetError("Internal error (TLR)");
                return(response);
            }

            var signinCredentials = new SigningCredentials(Settings.JwtSigningKey, SecurityAlgorithms.HmacSha256);

            var tokeOptions = new JwtSecurityToken(
                issuer: Settings.JwtIssuer,
                audience: Settings.JwtAudience,
                claims: new List <Claim>()
            {
                // ClaimTypes.Name serialized as "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
                // and it is too long
                // new Claim(ClaimTypes.Name, "name-test"),
                new Claim(Settings.JwtUserNameClaimName, res.Data.Name),
                new Claim(Settings.JwtUserIdClaimName, res.Data.PublicId.ToString()),
            },
                expires: DateTime.Now.Add(Settings.JwtExpires),
                signingCredentials: signinCredentials
                );

            var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

            return(new LoginResponse()
            {
                Data = tokenString
            });
        }
        public virtual ClientRequestIdentity SetIdentity(HttpContext httpContext)
        {
            var clientId = "anon";

            if (httpContext.Request.Headers.Keys.Contains(_options.ClientIdHeader, StringComparer.CurrentCultureIgnoreCase))
            {
                clientId = httpContext.Request.Headers[_options.ClientIdHeader].First();
            }

            string clientIp;

            try
            {
                var ip = _ipParser.GetClientIp(httpContext);
                if (ip == null)
                {
                    throw new Exception("IpRateLimitMiddleware can't parse caller IP");
                }

                clientIp = ip.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("IpRateLimitMiddleware can't parse caller IP", ex);
            }

            return(new ClientRequestIdentity
            {
                ClientIp = clientIp,
                Path = httpContext.Request.Path.ToString().ToLowerInvariant(),
                HttpVerb = httpContext.Request.Method.ToLowerInvariant(),
                ClientId = clientId
            });
        }
        public override ClientRequestIdentity SetIdentity(HttpContext httpContext)
        {
            var extractedTenantIds = httpContext.GetTenantIds();
            var tenantId           = extractedTenantIds.Count() > 0 ? extractedTenantIds.First().ToString() : "anon";

            var clientIp = String.Empty;

            try
            {
                var ip = ipAddressParser.GetClientIp(httpContext);

                if (ip == null)
                {
                    throw new Exception("IpRateLimitMiddleware can't parse caller IP");
                }

                clientIp = ip.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("IpRateLimitMiddleware can't parse caller IP", ex);
            }

            return(new ClientRequestIdentity
            {
                ClientIp = clientIp,
                Path = httpContext.Request.Path.ToString().ToLowerInvariant(),
                HttpVerb = httpContext.Request.Method.ToLowerInvariant(),
                ClientId = tenantId.ToLowerInvariant()
            });
        }
Beispiel #4
0
        private static ClientRequestIdentity SetIdentity(HttpContext httpContext)
        {
            var clientId = "anon";

            if (httpContext.Request.Headers.Get(Options.ClientIdHeader) != null)
            {
                clientId = httpContext.Request.Headers.GetValues(Options.ClientIdHeader).First();
            }

            var clientIp = string.Empty;

            try
            {
                var ip = IpParser.GetClientIp(httpContext);
                if (ip == null)
                {
                    throw new Exception("IpRateLimitMiddleware can't parse caller IP");
                }

                clientIp = ip.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("IpRateLimitMiddleware can't parse caller IP", ex);
            }

            return(new ClientRequestIdentity
            {
                ClientIp = clientIp,
                Path = httpContext.Request.Path.ToString().ToLowerInvariant(),
                HttpVerb = httpContext.Request.HttpMethod.ToLowerInvariant(),
                ClientId = clientId
            });
        }
Beispiel #5
0
        public virtual ClientRequestIdentity SetIdentity(HttpContext httpContext)
        {
            string clientId = "";

            if (httpContext.Request.Headers.Keys.Contains(_options.ClientIdHeader))
            {
                clientId = httpContext.Request.Headers[_options.ClientIdHeader].First();
            }

            if (httpContext.User.Identity.IsAuthenticated)
            {
                clientId = httpContext.User.Identity.Name;
            }

            if (string.IsNullOrWhiteSpace(clientId))
            {
                clientId = "anon";
            }

            var clientIp = string.Empty;

            try
            {
                var ip = _ipParser.GetClientIp(httpContext);
                if (ip == null)
                {
                    throw new Exception("IpRateLimitMiddleware can't parse caller IP");
                }

                clientIp = ip.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("IpRateLimitMiddleware can't parse caller IP", ex);
            }

            return(new ClientRequestIdentity
            {
                ClientIp = clientIp,
                Path = httpContext.Request.Path.ToString().ToLowerInvariant(),
                HttpVerb = httpContext.Request.Method.ToLowerInvariant(),
                ClientId = clientId
            });
        }
Beispiel #6
0
        public bool RateExceeded(HttpContext context, IPRateLimitingSetting setting, out int retryAfter)
        {
            retryAfter = 0;
            var path   = context.Request.Path;
            var method = context.Request.Method.ToLower();

            var clientIP = _ipParser.GetClientIp(context);

            //System.Diagnostics.Debugger.Break();

            if (_ipParser.ContainsIp(setting.IPWhitelist, clientIP.ToString()))
            {
                return(false);
            }

            if (_ipParser.ContainsIp(setting.IPBlockedlist, clientIP.ToString()))
            {
                return(true);
            }

            var generalRuleExists = setting.GeneralRules.FirstOrDefault(q => q.Verbs.ToLower().Contains(method) && q.Path == path);

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

            if (!IpRateLimiterDictionary.TryGetValue(clientIP.ToString(), out IPRateCounter existedRate))
            {
                var iPRateCounter = new IPRateCounter()
                {
                    Count = 1, CreatedAt = DateTime.Now
                };
                IpRateLimiterDictionary.AddOrUpdate(clientIP.ToString(), iPRateCounter, (key, oldValue) => iPRateCounter);
                return(false);
            }


            var now       = DateTime.Now.AddSeconds(-generalRuleExists.PeriodTime);
            var createdAt = existedRate.CreatedAt;

            if (createdAt > now)
            {
                retryAfter = (int)(now - createdAt).TotalSeconds;
                if (existedRate.Count >= generalRuleExists.Limit)
                {
                    return(true);
                }
                else
                {
                    existedRate.Count++;
                    return(false);
                }
            }
            else
            {
                existedRate.Count     = 1;
                existedRate.CreatedAt = DateTime.Now;
                IpRateLimiterDictionary.AddOrUpdate(clientIP.ToString(), existedRate, (key, oldValue) => existedRate);
                return(false);
            }
        }