Content Security Policy (CSP)

"Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks."

Enable CSP

Send the Content-Security-Policy HTTP header via .htaccess file

Header set Content-Security-Policy "default-src 'self';"

or use a <meta> element as shown here

<meta http-equiv="Content-Security-Policy" content="default-src 'self';" />

See also: Discussion about CSP in HTTP header vs CSP in meta tag on Stackoverflow



Allow everything but only from the same origin

default-src 'self';

Allow Google Analytics, Google AJAX CDN and Same Origin

script-src 'self';

Starter Policy

  • Allows images, scripts, AJAX, form actions, and CSS from the same origin
  • Does not allow any other resources to load (eg object, frame, media, etc)
default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';base-uri 'self';form-action 'self';

How to handle inline scripts

a) With nonces

  • Generate the nonce on server site every request.
  • Length should be > 128bit.
script-src 'nonce-${cspNonce}'
<script nonce="${cspNonce}">
    const inline1 = "Hello";
<script nonce="${cspNonce}">
    const inline2 = "Nonces";

b) With hashes

script-src 'sha256-tk2RMpooRG6MsiJVeTM37W8UhPMYIPoh6O2rqMnTyH4=' 'sha256-NZBfn5BmBvL+v41TgdkGknEcbpovV8wWu4gYsqxtk00='
    const inline1 = "Hello";
    const inline2 = "Hashes";

CSP with AdSense is not possible

See also