Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Csp Laravel Package

spatie/laravel-csp

Set Content Security Policy (CSP) headers in Laravel to control which scripts, styles, and resources can load and where they can send data. Helps prevent XSS and malicious third-party scripts. Includes report-only mode, nonces, and easy config.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require spatie/laravel-csp
    php artisan vendor:publish --tag=csp-config
    
  2. Enable CSP Globally: Register the middleware in bootstrap/app.php:
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(Spatie\Csp\AddCspHeaders::class);
    })
    
  3. Configure Default Presets: Edit config/csp.php to include presets (e.g., Spatie\Csp\Presets\Basic::class).
    'presets' => [
        Spatie\Csp\Presets\Basic::class,
        Spatie\Csp\Presets\Google::class, // Add third-party services
    ],
    

First Use Case

Block Inline Scripts/Styles: Add a directive to config/csp.php to restrict inline scripts:

'directives' => [
    [Directive::SCRIPT, [Keyword::SELF, Keyword::NONCE]],
],

Then use @cspNonce in Blade:

<script @cspNonce>
    console.log('Safe inline script');
</script>

Implementation Patterns

Core Workflows

  1. Middleware Integration:

    • Apply CSP globally via AddCspHeaders middleware.
    • Override presets per route:
      Route::get('/admin', AdminController::class)
          ->middleware(AddCspHeaders::class . ':' . AdminPreset::class);
      
  2. Blade Directives:

    • Inject CSP meta tags:
      <head>
          @cspMetaTag
      </head>
      
    • Generate nonces for inline scripts/styles:
      <style @cspNonce>
          body { color: red; }
      </style>
      
  3. Dynamic Policies:

    • Use Csp::addDirective() in controllers/middleware:
      use Spatie\Csp\Csp;
      
      public function __construct() {
          Csp::addDirective(Directive::SCRIPT, Keyword::NONCE);
      }
      

Integration Tips

  • Vite/Laravel Mix: Disable CSP during hot reloading (set CSP_ENABLED_WHILE_HOT_RELOADING=true in .env).
  • Third-Party Services: Use existing presets (e.g., GoogleFonts, Stripe) or create custom ones.
  • Reporting Violations: Configure report_uri in config/csp.php to log CSP violations:
    'report_uri' => env('CSP_REPORT_URI', 'https://your-report-endpoint.com'),
    

Gotchas and Tips

Pitfalls

  1. Nonce Mismatches:
    • Forgetting @cspNonce on inline scripts/styles triggers violations.
    • Fix: Use @cspNonce or disable nonces (CSP_NONCE_ENABLED=false).
  2. Overly Restrictive Policies:
    • Blocking unsafe-inline or unsafe-eval may break legacy scripts.
    • Fix: Test policies in report-only mode first:
      'report_only_presets' => [Spatie\Csp\Presets\Basic::class],
      
  3. Caching Headers:
    • CSP headers must be dynamic (e.g., per route). Avoid static caching.
    • Fix: Use middleware per route or dynamic directives.

Debugging

  • Violation Reports: Check report_uri logs for blocked resources. Example:
    {
      "csp-report": {
        "document-uri": "https://example.com",
        "violated-directive": "script-src",
        "effective-directive": "script-src 'self'",
        "original-policy": "'self'",
        "disposition": "enforce",
        "blocked-uri": "inline:console.log('hacked')"
      }
    }
    
  • Testing: Use Chrome DevTools (Console > Security > Content Security Policy) to validate policies.

Extension Points

  1. Custom Presets: Extend Spatie\Csp\Preset to create service-specific policies:
    namespace App\Csp;
    
    use Spatie\Csp\Directive;
    use Spatie\Csp\Keyword;
    use Spatie\Csp\Preset;
    
    class CustomServicePreset implements Preset {
        public function getDirectives(): array {
            return [
                [Directive::CONNECT, ['api.custom-service.com']],
            ];
        }
    }
    
  2. Dynamic Directives: Modify policies at runtime (e.g., based on user roles):
    if (auth()->user()->isAdmin()) {
        Csp::addDirective(Directive::SCRIPT, ['admin-panel.com']);
    }
    
  3. Reporting Endpoints: Add custom endpoints to reporting_endpoints:
    'reporting_endpoints' => [
        'default' => 'https://example.com/csp-reports',
        'analytics' => 'https://analytics.example.com/report',
    ],
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony