Hackernoon logoNodeJS Security Headers: 101 by@akash_tomar

NodeJS Security Headers: 101

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.
image
Akash Tomar Hacker Noon profile picture

Akash Tomar

Bio is WIP

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:

image

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:

image

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!

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.