Content Security Policy (CSP)

9 min read

Content Security Policy (CSP) is a set of guidelines and security features that website owners can implement to protect their websites against common web vulnerabilities such as cross-site scripting (XSS) attacks, code injection attacks, and clickjacking.

CSP works by defining a whitelist of trusted sources for specific types of content on a website, such as scripts, stylesheets, images, fonts, and media files. It helps prevent the execution of malicious scripts from unrecognized sources by only allowing content to be loaded from trusted sources defined in the CSP.

When a web page is loaded, the browser checks the CSP header sent by the server to determine which sources are allowed for each type of content. Any violations of the defined policy are blocked and reported to the server.

CSP provides several directives that can be used to define the allowed sources for different types of content. Some commonly used directives include:

  1. script-src: This directive controls the sources from which JavaScript code can be loaded and executed.
  2. style-src: This directive controls the sources from which stylesheets can be loaded.
  3. img-src: This directive controls the sources from which images can be loaded.
  4. font-src: This directive controls the sources from which fonts can be loaded.
  5. media-src: This directive controls the sources from which media files can be loaded.
  6. default-src: This directive sets the default sources for all types of content if no specific directive is defined.

By implementing a robust CSP, website owners can significantly reduce the risk of various web attacks and enhance the overall security of their websites.