I use node.js, passport and jwt bearer token to protect my routes. What I don't have yet is rate limiting and blocking of ip/user if too many false attempts. What's the best way to implement it for my setup?
I want to give it a try with rate-limiter-flexible. But how can I integrate eg the Login Example from here: https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection in my setup below?
helpers/rateLimiter.js
const express = require('express');
const redis = require('redis');
const { RateLimiterRedis } = require('rate-limiter-flexible');
/* What goes here? Example https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection doesn't seem to apply */
Those are my routes:
routes/index.js
const express = require('express');
const router = require('express-promise-router')();
const passport = require('passport');
const passLogin = passport.authenticate('local-login', { session: false, failWithError: true });
const { rateLimiter } = require('../helpers/rateLimiter');
...
router.route('/v1/login')
.post( rateLimiter, passLogin, function(err, req, res, next) {
return res.status(401).send({ status: 401, success: false })
}, controller.login );
router.route('/v1/abc/search')
.post( passJWT_ABC, function(err, req, res, next) {
return res.status(401).send({ status: 401, success: false })
}, controller.search );
You should export middleware in this case.
const express = require('express');
const redis = require('redis');
const { RateLimiterRedis } = require('rate-limiter-flexible');
async function loginRoute(req, res) {
// code from example https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection
}
export default async (req, res, next) => {
try {
await loginRoute(req, res);
next();
} catch (err) {
res.status(500).end();
}
}
And then you should take care of how authorise()
, user.isLoggedIn
and user.exists
checks work with your application login approach.
There is an example with passport-local, should be useful for you as well https://github.com/passport/express-4.x-local-example/blob/67e0f735fc6d2088d7aa9b8c4eb25bc0052653ec/server-secure.js
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.