04 / 04

What is CSP (Content Security Policy) and how does HTML interact with it?

Content Security Policy (CSP) in HTML

Content Security Policy (CSP) is a powerful security feature that helps prevent cross-site scripting (XSS), data injection, and other code-injection attacks. It works by telling the browser which resources (scripts, styles, images, etc.) are allowed to load and execute on a web page.

How CSP Works with HTML
  1. 1

    Defined via <meta> or HTTP headers: You can declare a CSP inside the HTML <head> using <meta http-equiv="Content-Security-Policy"> or more commonly via server-set HTTP headers.

  2. 2

    Restricts inline scripts/styles: By default, CSP blocks inline JavaScript (<script>alert(1)</script>) and inline CSS unless explicitly allowed.

  3. 3

    Controls external resources: CSP can restrict which domains scripts, styles, fonts, images, and iframes can be loaded from.

  4. 4

    Mitigates XSS: Even if an attacker injects malicious HTML/JS, a strict CSP prevents it from running by blocking inline code or unauthorized sources.

Example: CSP in HTML

In short: CSP works alongside HTML by restricting what code and resources can run. It provides a strong defense against XSS and data injection attacks, but must be carefully configured to avoid breaking legitimate functionality.