Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Few words before we start
When you create a website or application, it means you are ready to show it thousands of people on the internet. Your customer/audience may be legit, but some of them will try to tamper your application. So you need to follow the following golden rules
- âNever trust your audience when it comes to your applicationâs securityâ
- Always validate the user input before getting it into the server.
- Always encode the user inputs before printing them on to the screen.
The helmet is really like a helmet for your applications. It protects your application by setting up various HTTPÂ headers.
const express = require('express')const helmet = require('helmet')const app = express()app.use(helmet())
The express-session middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data.
var app = express()app.set('trust proxy', 1) // trust first proxyapp.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true }}))
A simple cookie-based session middleware, that allows storing cookies.It does not require any database/resources on the server side, though the total session data cannot exceed the browserâs max cookie size.
var cookieSession = require('cookie-session')var express = require('express')var app = express()app.use(cookieSession({ name: 'session', keys: [ /* secret keys */ ], // Cookie Options maxAge: 24 * 60 * 60 * 1000 // 24 hours}))
Object schema description language and validator for JavaScript objects by hapi. It is very useful to validate the user input.
const Joi = require('joi');const schema = Joi.object().keys({ username: Joi.string().alphanum().min(3).max(30).required(), password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/), access_token: [Joi.string(), Joi.number()], birthyear: Joi.number().integer().min(1900).max(2013), email: Joi.string().email({ minDomainAtoms: 2 })}).with('username', 'birthyear').without('password', 'access_token');// Return result.const result = Joi.validate({ username: 'abc', birthyear: 1994}, schema);// result.error === null -> valid// You can also pass a callback which will be called synchronously with the validation result.Joi.validate({ username: 'abc', birthyear: 1994}, schema, function(err, value) {}); // err === null -> valid
You may aware of the brute force attack. express-rate-limit is a middleware for express routes that rate-limits incoming requests, increasing the delay with each request in a Fibonacci-like sequence.
const rateLimit = require("express-rate-limit");
app.enable("trust proxy");const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
// apply to all requestsapp.use(limiter);
A middleware that checks JWT tokens for permissions. It is very useful to build a user access control system.
var guard = require('express-jwt-permissions')()
app.use(guard.check('admin'))
Express middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection.
var express = require('express'), bodyParser = require('body-parser'), mongoSanitize = require('express-mongo-sanitize');var app = express();app.use(bodyParser.urlencoded({ extended: true}));app.use(bodyParser.json());// To remove data, use:app.use(mongoSanitize());// Or, to replace prohibited characters with _, use:app.use(mongoSanitize({ replaceWith: '_'}))
Express middleware to protect against HTTP Parameter Pollution attacks. To know more read Chetan Karandeâs slides
var express = require('express'), bodyParser = require('body-parser');var app = express();// ...var hpp = require('hpp');// ...// Make sure the body is parsed beforehand.app.use(bodyParser.urlencoded());
app.use(hpp()); // <- THIS IS THE NEW LINE
// Add your own middlewares afterwards, e.g.:app.get('/search', function(req, res, next) { /* ... */ });// They are safe from HTTP Parameter Pollution now.
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.
var express = require('express'), bodyParser = require('body-parser'), dotenv = require('dotenv');var app = express();
dotenv.config();dotenv.config({ path: "../.env"});
csurf
The csurf is a CSRF protection middleware.
var cookieParser = require('cookie-parser')var csrf = require('csurf')var bodyParser = require('body-parser')var express = require('express')// setup route middlewaresvar csrfProtection = csrf({ cookie: true})var parseForm = bodyParser.urlencoded({ extended: false})// create express appvar app = express()// parse cookies// we need this because "cookie" is true in csrfProtectionapp.use(cookieParser())app.get('/form', csrfProtection, function(req, res) { // pass the csrfToken to the view res.render('send', { csrfToken: req.csrfToken() })})app.post('/process', parseForm, csrfProtection, function(req, res) { res.send('data is being processed')})
I wish you happy coding.
If you enjoyed this article, please clap it up and share it so that others can find it!
Express JS Important NPM Packages Related to Security was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.