[英]How to increase the blocking time period after being rate limited using express-rate-limit in Node js?
The express-rate-limit
library will block connections from a client (let's say identified by IP) after surpassing certain amount of requests per time unit. express-rate-limit
库将在超过每个时间单位的一定数量的请求后阻止来自客户端的连接(假设由 IP 标识)。 It also blocks the connections for a time equivalent to the time unit.它还会在相当于时间单位的时间内阻塞连接。
So, if it is set to block connections after 120 requests per minute;因此,如果设置为每分钟 120 个请求后阻止连接; it will also block the IP for a minute.
它还会阻塞 IP 一分钟。 How could I extend the blocking time?
我怎样才能延长阻塞时间?
Here is my current example:这是我当前的示例:
...
var express = require('express');
var app = express();
const RateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
limiter = new RateLimit({
store: new RedisStore({
expiry: 60
}),
max: 120
});
app.use(limiter);
...
Here, I am also using rate-limit-redis
, its expiry
parameter overwrites the windowMs
parameter of express-rate-limit
.这里我也是用
rate-limit-redis
,它的expiry
参数覆盖了express-rate-limit
的windowMs
参数。
By using onLimitReached
callback, you can keep a record of the time in which the IP is unblocked again.通过使用
onLimitReached
回调,您可以记录 IP 再次解锁的时间。 Then, you can write another middleware that checks when the unblocking date is reached.然后,您可以编写另一个中间件来检查何时达到解锁日期。
In the example below, bannedIPs
keeps the record of the time in which the IP is unblocked again, and banner
is the middleware that uses the time to block the IP according to the current date.在下面的示例中,
bannedIPs
记录了 IP 再次被解锁的时间, banner
是使用该时间根据当前日期对 IP 进行解锁的中间件。
...
var express = require('express');
var app = express();
const RateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
// Keep the IPs that are banned
const bannedIPs = {};
limiter = new RateLimit({
store: new RedisStore({
expiry: 60
}),
onLimitReached: function(req, res, options) {
// The IP will be unblocked again in an hour (60*60*1000)
bannedIPs[req.ip] = +new Date() + 60*60*1000;
},
max: 120
});
banner = function(req, res, next) {
// If the current Date is still before than the unblocking date,
// send a 429 message indicating too many requests
if (bannedIPs[req.ip] >= +new Date()) {
res.status(429).send("Sorry, too many requests: " + new Date(bannedIPs[req.ip]));
} else {
next();
}
}
app.use(banner);
app.use(limiter);
...
There is a lot of space of improvement, eg removing the IPs once they are no longer blocked, and maybe store the keys in Redis so they are persistent after restarting the server.有很大的改进空间,例如一旦不再被阻止就删除IP,并且可能将密钥存储在Redis中,以便在重新启动服务器后保持不变。 But, this will give you a starting point.
但是,这将为您提供一个起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.