Secure Node JS Rest API

Gaurav Talele
4 min readMar 20, 2020

Hello Folks, This is friday. Today we will discuss how we can secure our rest api against various attacks. You might already know that these attacks are very harmful and you need to make your application (or API) secure, as much as you can. But how exactly…?

Their are DOS Attacks, XSS, SQL/NoSQL Injection Attacks.

You might already know that these attacks are very harmful and you need to make your application (or API) secure, as much as you can. But how exactly?

Denial-Of-Service (DOS) Attacks

DOS Attack will crash / shut down a network, or machine, making it inaccessible. Which means users won’t be able to access your application, for example. Attacker accomplishes this by constantly sending requests, creating traffic and sending plenty of all kind of a informations.
With DOS attacks, attackers can either make your service slower or crash it entirely.

Cross-Site Scripting (XSS) Attacks

XSS Attacks are a type of injections. Attackers inject malicious scripts into the forms of a browser side script. Usually they occur on input forms when those forms are not validated or encoded. With XSS attacks, attacker can gain access to cookies, session tokens or / and other sensitive data. As well, these scripts can rewrite HTML content of a page.

Brute Force Attacks

Brute force attack is a method used to obtain sensitive data such as user password or personal identification number (PIN). In these attacks, attackers most likely rely on automated software to generate a large numbers guesses to the value of desired data.

SQL/NoSQL Injection Attacks

SQL/NoSQL Injection (SQLi) Attacks is a type of an injection attack. SQL/NoSQL Injection makes it possible for attacker to execute malicious SQL/NoSQL statements. Attackers can achieve SQL/NoSQL Injection attack simply by inserting SQL/NoSQL commands (queries) to a specific fields on your application that is connected to a database (POST request for logging in for example).With SQL/NoSQL Injection Attacks, attackers can bypass authentication, authorization, retrieve the content of the entire SQL/NoSQL database, add, modify, delete data in database.

The Question is how to prevent these attacks…?

Preventing DOS Attacks:

  1. First thing to consider when dealing with DOS attacks prevention is to limit the actual payload that user can submit to your app / api / service. You can limit the body payload using body-parser. If you are using ExpressJS as your backend framework, then you are golden. ExpressJS comes with built-in body-parser that you can use.
const express = require('express');
const app = express();app.use(express.json({ limit: '10kb' })); // Body limit is 10

2.Another useful express feature is express-rate-limit dependency. This dependency lets you set rate limit for users. So basically, you can set maximum amount of requests for each user, after user uses all of his requests, you can lock him out for certain amount of time.

— npm install express-rate-limit

const limit = rateLimit({
max: 100,// max requests
windowMs: 60 * 60 * 1000, // 1 Hour
message: 'Too many requests' // message to send
});
app.use('/routeName', limit); // Setting limiter on specific route

Preventing XSS Attacks:

  1. First of all, you can sanitize user data, on input. This is very easy to implement, and we can use another useful dependency called xss-clean.
    This dependency will prevent users from inserting HTML & Scripts on input.

— npm install xss-clean

app.use(xss());

2. Give your project special HTTP headers using helmet dependency. Helmet is a collection of middleware functions. By default, not all of the middleware functions are included, but you can enable rest of them manually. You can check this link to see other middleware functions.

— npm install helmet

app.use(helmet());

Preventing Brute Force Attacks

  1. One of the most efficient way to help you to deal with brute force attacks, is to set limit to login attempts, or anything related to authentication that requires users to insert their passwords, special codes or PINs.
  2. Next up, and again, if you are using ExpressJS, you could implement express-rate-limit dependency. Which we did indeed implemented in DOS attacks prevention. But this dependency works both for Brute Force attacks and DOS attacks.
  3. To slower down and make life a little bit harder for attackers when guessing sensitive data (passwords, PINs), you could implement bcrypt dependency. Bcrypt will encrypt sensitive data such as passwords and it will make them harder to guess. Bcrypt is a little bit complex dependency, but if you want to learn more (and you should) checkout this link.
  4. Another thing that will make brute force attacks less likely is implementing 2-Step verification process, or two-factor authentication. It does take couple of lines of codes to implement this, so here is the link that will help you out with it!

Preventing SQL/NoSQL Injection Attacks

  1. Either if you are working with SQL or NoSQL database, you should sanitize your data.
    If you are working with SQL database, you should consider using node-mysql dependency. Learn more about node-mysql here.
    If you are working with NoSQL database (MongoDB) and ExpressJS, consider using express-mongo-sanitize dependency.

— npm install express-mongo-sanitize

app.use(mongoSanitize());

2. If working with MongoDB, use Object Data Modeling tool (ODM) Mongoose. Mongoose lets you define schemas and schema types for each one of your documents, making it secure from the beginning. Mongoose is pretty complex on it’s own, but if you want to dive deep into it, i’ll suggest you to check this link or get a crash course on it and learn it on the go.

Your main app file could look like this after you implemented these dependencies:

// Importing Dependencies
const express = require('express');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
const app = express();// Helmet
app.use(helmet());// Rate Limitingconst limit = rateLimit({
max: 100,// max requests
windowMs: 60 * 60 * 1000, // 1 Hour of 'ban' / lockout
message: 'Too many requests' // message to send
});
app.use('/routeName', limit); app.use(express.json({ limit: '10kb' }));

app.use(mongoSanitize());
app.use(xss()

Conclusion:

These are just couple of methods, practices that you can use in your own project to make your application or API secure. You can explore each one of these more in depth following references i included or simply researching more about them on your own.

--

--

Gaurav Talele

An ambitious Full Stack evangelist in Angular, Typescript, Spring Boot Node JS, C#, Dot Net Core WEB API, MS SQL, Redis, MongoDB, RabbitMQ, Docker and AWS.