限速以防止ExpressJS中的恶意行为

Jos*_*ith 8 javascript rate-limiting node.js express

有人让我意识到我正在处理的应用程序中的一些缺陷(主要是在我的前端JavaScript中),这样就可以让你一次点击大量的按钮然后发出大量的事务.电子邮件.这显然不太好.

我认为在ExpressJS中处理此问题的一种方法是使用app.all()计算在特定时间范围内发生的请求数.我将它存储在带有时间戳的会话元数据中,如果在Y时间内发生超过X个请求,我会将它们关闭一段时间,直到限制到期为止.

有没有人之前做过这个或有任何提示/提示来帮助我?一些容易进出我的应用程序的东西更可取.谢谢!

Ker*_*mes 2

Collate您可以在网页中使用该对象。

function Collate(timeout) {
  this.timeout = timeout || 1000;
}
Collate.prototype = {
  time: 0,

  idle: function() {
    var t = new Date().getTime();
    return (t - this.time > this.timeout && (this.time = t));
  },

  prefer: function(func) {
    this.func = func;
    clearTimeout(this.timer);
    this.timer = setTimeout(func, this.timeout);
  }
};
Run Code Online (Sandbox Code Playgroud)

如果您希望某个函数运行一次并且在接下来的 1 秒内不再运行。就像如果你想阻止用户多次提交表单,你可以这样做:

var timer = new Collate(3000);  //3 seconds
button1.onclick = function() {
    if(timer.idle()) {
        button1.form.submit();
    } else alert("Don't click too quickly!");
}

//or on the form tag

<script>var submitTimer = new Collate(3000);</script>
<form action="post" onsubmit="return submitTimer.idle();">
Run Code Online (Sandbox Code Playgroud)

如果您期望一个事件多次触发并且只想对其最后一次触发做出反应。就像如果您想在用户完成输入后进行搜索,您可以这样做:

var timer = new Collate(700); //0.7 seconds
textfield1.onkeyup = function() {
    timer.prefer(function() {
        autocomplete.search(textfield1.value);
    });
};
Run Code Online (Sandbox Code Playgroud)

  • 像这样的客户端解决方案只能防止用户的意外操作,但不一定能防止“恶意”用户的操作(他们可以只手动发送 POST 和 GET)。 (4认同)