Content Security Policy (CSP) Headers
Network SecurityContent Security Policy is an HTTP response header that tells the browser exactly which sources of content are allowed to load on your page. You define rules for scripts, stylesheets, images, fonts, frames, and other resource types, specifying which domains they can come from. For example, a CSP might say "only load JavaScript from my own domain and Google Analytics, only load images from my domain and my CDN, and never execute inline scripts." When the browser encounters content that violates these rules, like a script injected by an attacker or a malicious iframe, it blocks it and reports the violation. CSP is delivered as a Content-Security-Policy HTTP header from your server and acts as a last line of defense against content injection attacks, even if an attacker manages to inject HTML into your page.
Why It Matters
Cross-site scripting (XSS) remains one of the most prevalent web application vulnerabilities year after year, and CSP is the strongest browser-level defense against it. Even the most carefully written application code can have an XSS vulnerability slip through, a user comment rendered without proper escaping, a URL parameter reflected in the page, or a third-party library with a flaw. CSP ensures that even if malicious code gets injected into your HTML, the browser will refuse to execute it because it does not match your approved sources. It also prevents data exfiltration by controlling which domains your page can send data to. For applications that handle financial transactions, personal health information, or sensitive business data, CSP is an essential layer of protection that catches what your code misses.
What Happens Without It
In 2018, British Airways suffered a breach where attackers injected a malicious script into the airline's payment page. The script skimmed credit card details from approximately 380,000 customers as they typed their payment information, sending the stolen data to an attacker-controlled server. A properly configured Content Security Policy would have blocked the injected script from executing (it came from an unauthorized domain) and would have prevented the page from sending data to the attacker's server. The attack, attributed to the Magecart group, resulted in a proposed 183 million pound fine under GDPR. Similar Magecart attacks have hit Ticketmaster, Newegg, and hundreds of other e-commerce sites, virtually all of which lacked adequate CSP headers.
Every app I build includes Content Security Policy headers by default.