05. CSP Content Security Policy
Introduction
Section titled “Introduction”Content Security Policy (CSP) is a security feature that helps prevent cross-site scripting (XSS) attacks by controlling which resources can be loaded and executed. CSP is implemented via HTTP headers or meta tags and restricts the sources from which content can be loaded, significantly improving website security.
Basic Implementation
Section titled “Basic Implementation”Meta Tag
Section titled “Meta Tag”<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">HTTP Header
Section titled “HTTP Header”Content-Security-Policy: default-src 'self'; script-src 'self'Common Directives
Section titled “Common Directives”default-src
Section titled “default-src”Default source list:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">script-src
Section titled “script-src”Allowed script sources:
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">style-src
Section titled “style-src”Allowed stylesheet sources:
<meta http-equiv="Content-Security-Policy" content="style-src 'self' 'unsafe-inline'">img-src
Section titled “img-src”Allowed image sources:
<meta http-equiv="Content-Security-Policy" content="img-src 'self' https:">Common Policies
Section titled “Common Policies”Strict Policy
Section titled “Strict Policy”<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:">Allow External Scripts
Section titled “Allow External Scripts”<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://cdn.example.com">Best Practices
Section titled “Best Practices”Start Restrictive
Section titled “Start Restrictive”<!-- Good: Restrictive policy --><meta http-equiv="Content-Security-Policy" content="default-src 'self'">Report Violations
Section titled “Report Violations”<meta http-equiv="Content-Security-Policy" content="default-src 'self'; report-uri /csp-report">