在特定IP上应用速率限制登录api不是gloablly

时间:2018-03-30 06:22:19

标签: javascript node.js express brute-force rate-limiting

我正在使用express-rate-limit@2.11.0模块并且它工作正常但它阻止了api全局而不是特定的api从它获得命中。

我的代码:

const limiter = new RateLimit({
        windowMs: 15*60*1000,
        max: 100,
        delayMs: 0,
        message: '==> You have made too many attempts in a short period of time, please try later',
        handler: (req, res) => {
            res.format({
                json: () => {
                    res.status(429).json({
                        message: 'You have made too many attempts in a short period of time, please try later'
                    });
                }
            });
        },
        onLimitReached: (req, res, options) => {
            logger.error(options.message, resolveLogger({
                reqURL: req.url,
                statusCode: options.statusCode
            }));
        }
    });

有些人可以建议我如何将其限制为仅限于ip

1 个答案:

答案 0 :(得分:0)

如评论中所述,最好将反向代理,负载均衡器或任何其他入口点的费率限制在您的node.js app

如果这不适合您的应用,我建议rate-limiter-flexible

const { RateLimiterMemory } = require('rate-limiter-flexible');

const opts = {
  points: 100, // 100 points
  duration: 15*60, // Per 15 minutes
};

const rateLimiter = new RateLimiterMemory(opts);

const rateLimiterMiddleware = (req, res, next) => {
  const isIpLimited = isIpLimited(req.ip);
  if (isIpLimited) {
    // Consume 1 point for each request
    rateLimiter.consume(req.ip)
      .then(() => {
        // There was enough remaining points
        next();
      })
      .catch((rejRes) => {
        // All points consumed
        const secs = Math.round(rejRes.msBeforeNext / 1000) || 1;
        res.set('Retry-After', String(secs));
        res.status(429).send('Too Many Requests');
      });
  } else {
    next();
  }
};

app.use(rateLimiterMiddleware);

注意:内存限制器适用于当前进程内存。还有Cluster,Redis和Mongo限制器,它们共享状态。