Laravel Csp
Laravel Csp stats
- Downloads
- 2.6M
- Stars
- 639
- Open Issues
- 0
- Forks
- 57
Add CSP headers to the responses of a Laravel app
Laravel CSP: Secure Your App with Content Security Policies
The spatie/laravel-csp package is a powerful tool for managing Content Security Policy (CSP) headers in Laravel applications, enhancing the security by controlling the sources from which your application can load resources.
Key Features
- Flexible Policy Definitions: Define and manage CSP directives easily using policy classes.
- Dynamic Nonce Support: Automatically handles nonces for inline scripts and styles, ensuring they align with CSP requirements.
- Configurable Response Headers: Choose between standard CSP headers or meta tags within HTML documents.
- Development and Production Modes: Supports different policies for development and production, with options to report only mode for testing.
- Integration with Laravel Vite: Seamlessly integrates with Laravel Vite for nonce generation during asset compilation.
Installation
Install the package via composer:
composer require spatie/laravel-csp
Publish the configuration file:
php artisan vendor:publish --tag=csp-config
Register the middleware in your HTTP kernel or on specific routes to apply CSP headers globally or conditionally.
Usage Overview
- Define CSP Policies: Extend the basic policy class to customize the sources your application should accept scripts, styles, images, etc., from.
- Apply Middleware: Attach the
Spatie\Csp\AddCspHeadersmiddleware to your web middleware group or specific routes. - Test Policies: Set policies in report-only mode to monitor potential issues without impacting users.
- Handle Nonces: Utilize the built-in nonce generator or integrate with Laravel Vite for managing script and style tags securely.
Policy Customization
You can extend the basic policy class to specify your own directives:
namespace App\Support; use Spatie\Csp\Directive;use Spatie\Csp\Policies\Policy; class MyCustomPolicy extends Policy{ public function configure() { $this->addDirective(Directive::SCRIPT, 'www.google.com'); }}
Set your custom policy in the csp.php config file to activate it across your application.
Inline Scripts and Styles
Use nonces generated by the package to include inline scripts and styles safely:
<!-- in a Blade view --><script nonce="{{ csp_nonce() }}"> // Your inline script here</script>
Integration with Vite
Configure a custom nonce generator using Laravel Vite's CSP support for a streamlined workflow between development and production environments.
Reporting and Debugging
Configure a reporting URI to capture and analyze policy violations, helping you refine your CSP strategy.
Conclusion
spatie/laravel-csp is an essential package for developers looking to enforce security practices through content security policies, providing robust tools for configuration and management tailored to modern web applications.