简体   繁体   中英

How to secure an open REST API from abuse in Node.js?

For example, I have a REST api endpoint written in Node.js. It can be accessed from a webpage for non-technical users, and it can also be accessed through command line using the curl command. It doesn't require any credentials to access it because it is intended to be open for anyone to access it. The problem I am trying to solve is how can I prevent someone maliciously access this REST API endpoint, for example pinging this api endpoint over and over again, or how to prevent ddos attacks.

Not necessary a programming question, let me know if there is a better place to ask this.

You say you want it to be open, but then you say you want it to be sort of open!

Throttling / auth tokens. Choose at least one, pref both.

Pinging and DOS attacks are different and have nothing to do with your API as such. Unless your info is valueable / highly competitive, something as simple as IP banning will go a long way.

Setup Rate Limiting if you cant have an auth on it.

You can use this if you are using express https://www.npmjs.com/package/express-rate-limit

Preventing DDOS is not that easy without using solutions like CloudFlare.

To secure your REST api, you can use middleware if you use express

const checkAuth = (req, res, next) => {
   // logic for checking auth
   if (authorized) {
    return next();
   }
   res.status(401).send('NEED AUTH');
 };
 router.post('/login', checkAuth, (req, res, next) => {
   // actual logic for login
 });

Update: regarding @Akarsh's answer, you can use multiple middleware before actual logic. For example, one for auth check, and one for rate limit

router.post('/logic', checkAuth, rateLimit, (req, res, next) => {});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM