使用Node和Express JS防止蛮力

Dav*_*ave 11 security login brute-force node.js express

我正在使用Node和Express JS构建一个网站,并希望限制无效的登录尝试.两者都可以防止在线破解并减少不必要的数据库调用.有什么方法可以实现这个?

Dav*_*ave 8

所以在做了一些搜索之后,我无法找到我喜欢的解决方案,所以我根据Trevor的解决方案和明确的野蛮人编写了自己的解决方案.你可以在这里找到它.


Ani*_*mir 8

带有 Redis 或 Mongo 的rate-limiter-flexible包,用于分布式应用程序和内存中或集群帮助

这是Redis的示例

const { RateLimiterRedis } = require('rate-limiter-flexible');
const Redis = require('ioredis');

const redisClient = new Redis({
  options: {
    enableOfflineQueue: false
  }
});

const opts = {
  redis: redisClient,
  points: 5, // 5 points
  duration: 15 * 60, // Per 15 minutes
  blockDuration: 15 * 60, // block for 15 minutes if more than points consumed 
};

const rateLimiter = new RateLimiterRedis(opts);

app.post('/auth', (req, res, next) => {
  const loggedIn = loginUser();
  if (!loggedIn) {
      // Consume 1 point for each failed login attempt
      rateLimiter.consume(req.connection.remoteAddress)
        .then((data) => {
          // Message to user
          res.status(400).send(data.remainingPoints + ' attempts left');
        })
        .catch((rejRes) => {
          // Blocked
          const secBeforeNext = Math.ceil(rejRes.msBeforeNext / 1000) || 1;
          res.set('Retry-After', String(secBeforeNext));
          res.status(429).send('Too Many Requests');
        });
  } else {
    // successful login
  }
});
Run Code Online (Sandbox Code Playgroud)


Tre*_*xon 6

也许这样的事情可能会帮助你开始.

var failures = {};

function tryToLogin() {
    var f = failures[remoteIp];
    if (f && Date.now() < f.nextTry) {
        // Throttled. Can't try yet.
        return res.error();
    }

    // Otherwise do login
    ...
}

function onLoginFail() {
    var f = failures[remoteIp] = failures[remoteIp] || {count: 0, nextTry: new Date()};
    ++f.count;
    f.nextTry.setTime(Date.now() + 2000 * f.count); // Wait another two seconds for every failed attempt
}

function onLoginSuccess() { delete failures[remoteIp]; }

// Clean up people that have given up
var MINS10 = 600000, MINS30 = 3 * MINS10;
setInterval(function() {
    for (var ip in failures) {
        if (Date.now() - failures[ip].nextTry > MINS10) {
            delete failures[ip];
        }
    }
}, MINS30);
Run Code Online (Sandbox Code Playgroud)

  • 您如何看待快速暴力等解决方案?https://npmjs.org/package/express-brute (2认同)