When the browser loads a page, it executes a lot of code to render the content. The code could be from the same origin as the root document, or a different origin. By default, the browser does not distinguish between the two and executes any code requested by a page regardless of the source. Attackers use this exploit to maliciously inject scripts to the page, which are then executed because the browser has no way of determining if the content is harmful. These situations are where a Content Security Policy (CSP) can provide protection.

CSP is an HTTP header that provides an extra layer of security against code-injection attacks, such as  cross-site scripting (XSS),  clickjacking, and other similar exploits. It facilitates the creation of an “allowlist” of trusted content and blocks the execution of code from sources not present in the allowlist. It also reports any policy violations to a URL of your choice, so that you can keep abreast of potential security attacks.

With the CSP header, you can specify approved sources for content on your site that the browser can load. Any code that is not from the approved sources, will be blocked from executing, which makes it considerably more difficult for an attacker to inject content and siphon data.

In this tutorial, you’ll review the different protections the CSP header offers by implementing one in an  example Node.js application. You’ll also collect JSON reports of CSP violations to catch problems and fix exploits quickly.


To follow this tutorial, you will need the following:

  • A recent version of Node.js installed on your machine. Follow the steps in the relevant  How To Install Node.js tutorial for your operating system to set up a Node.js development environment.

You should also use a recent browser version, preferably  Chrome, as it has the best support for  CSP level 3 directives at the time of writing this article (November 2020). Also, make sure to disable any third-party extensions while testing the CSP implementation so that they don’t interfere with the violation reports rendered in the console.

#node.js #programming

How to Secure Node.js Applications with a Content Security Policy
43.25 GEEK