Skip to the main content
{}
Back to all articles

Technical article

Content Security Policy in Laravel without breaking the site

Build a CSP from the origins and inline content you actually use, test in report-only mode and avoid broad unsafe exceptions.

By Codegenie2 minute read
  • Security & privacy
  • Content
  • Security
  • Policy
  • Laravel
  • breaking
Browser window with a shield and protected content elements.
In this article

Content Security Policy limits resources a page may load or execute. Inventory scripts, styles, forms and connections, observe a suitable policy, then enforce it. CSP complements safe output and authorisation.

Inventory by browser function

  • script-src: own bundles and external scripts.
  • style-src: stylesheets and inline styles from libraries.
  • connect-src: fetch, websockets and reporting.
  • img-src and font-src: only necessary sources.
  • form-action, base-uri and frame-ancestors: submission targets, base URL and embedding.

The example suits a page using its own external scripts and styles. object-src blocks plugins; review connect-src for the application. script-src self does not allow ordinary inline script blocks. Do not add a wildcard just to hide a violation.

Limited policy in response middlewareapp/Http/Middleware/SecurityHeaders.phpphp
$policy = [
    "default-src 'self'",
    "object-src 'none'",
    "connect-src 'self'",
    "font-src 'self'",
    "img-src 'self' data:",
    "style-src 'self'",
    "script-src 'self'",
    "frame-ancestors 'none'",
    "base-uri 'self'",
    "form-action 'self'",
];

$response->headers->set(
    'Content-Security-Policy',
    implode('; ', $policy)
);

Report-only observes, enforcement blocks

Send a candidate as Content-Security-Policy-Report-Only first. It does not block; without a reporting endpoint you collect no central reports. Then test Content-Security-Policy on representative pages. Keep an existing enforced policy while observing a stricter candidate.

Illustrative violation: an inline snippet

A widget injects inline code. Identify its owner and move your own code to an external bundle where appropriate. When necessary, use a hash for unchanging content or a cryptographically random nonce per response. A fixed nonce is unsuitable. With shared cached HTML, header and markup must stay paired; resolve that cache interaction first.

Check navigation, forms, consent and error pages and deliberately try a forbidden resource. Inspect CDN injections. Limit report data and retention: URLs may contain sensitive parameters. This sample needs application-specific review before production.

Example verification: PHP fragments were syntax-checked with PHP 8.5.11. Laravel execution and hosting behaviour were not tested; use a suitable test application and configuration.

Last updated:

Investigate an existing Laravel problem

Describe the issue and affected flow. Do not share passwords, customer data or production exports in the first contact.