NodeJS Security Headers: 101

Written by akash_tomar | Published 2020/04/15
Tech Story Tags: nodejs | javascript | web-development | security | programming | coding | tutorial | backend

TLDR NodeJS Security Headers: 101.1,578 reads/readable by Akash Tomar Bio is WIP. Headers and Content Security Policy can be used to reduce risk of cross-site-scripting and click-jacking. The helmet package has a good number of middlewares for setting http headers and CSP for most generic applications. One must be careful while setting these since misconfigured headers can cause more harm than good. For instance if you look into the X-DNS-Prefetch-Control header, you can turn it off.via the TL;DR App

When we talk about security wrt any web application its a multiple dimensional thing it will involve a number of different aspects:
  • Form validations
  • Response headers and Content Security Policy 
  • Transport layer encryption (https)
  • Cross Site Request Forgery Tokens/ JWTs
These are just a few there would be others as well if you have SSO integration and other features as per your use case.
Today, lets just look into the setting response headers and CSP for most generic applications. 
Default response headers of a basic NodeJS application will look like:
To start with a good base setting let's look into the helmet package. It has a good number of middlewares for setting http headers.
npm i helmet // to install helmet
const helmet = require(‘helmet’);
app.use(helmet());
Just using these two lines of code your response will look like:
One must be careful while setting these since misconfigured headers can cause more harm than good. For instance if you look into the X-DNS-Prefetch-Control header.
DNS prefetch greatly improves performance of your web page since it resolves DNS names even before the user actually clicks on the link, but it is considered as a information leakage vulnerability if you are creating a banking project so its better to turn it off.
Other header that helmet gives you by default are:
  • X-Frame-Options
  • Strict-Transport-Security
  • X-Download-Options
  • X-Content-Type-Options
  • X-XSS-Protection
Now that are look into something that is interesting and equally tricky, Content Security Policy
Modern web browsers allow you to restrict resources that are loaded using the Content-Security-Policy headers. It can be used to reduce risk of cross-site-scripting and click-jacking.
A very basic code example for using these header would be:
app.use(helmet.contentSecurityPolicy({
directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
    }
}));
For the above code snippet header will look like:
default-src 'self'; style-src 'self'; script-src 'self' 'unsafe-inline'
To find more details for other directive refer docs 
Hope this helps!
Happy Coding!

Written by akash_tomar | Bio is WIP
Published by HackerNoon on 2020/04/15