paragonie/csp-builder
Build and send Content-Security-Policy headers in PHP from JSON files, JSON strings, or arrays. CSP Builder makes it easy to define directives programmatically and integrate CSP into web apps to improve security.
laravel-csp) is limited in flexibility compared to this package, which supports fine-grained directives, nonce/hash generation, and reporting mechanisms (e.g., report-uri, report-to)..env + runtime overrides).injectCSPHeader() method is PSR-7 compatible, enabling seamless integration with Laravel’s middleware stack. Example:
namespace App\Http\Middleware;
use ParagonIE\CSPBuilder\CSPBuilder;
use Psr\Http\Message\ResponseInterface;
class CSPMiddleware extends \Closure
{
public function __invoke($request, \Closure $next): ResponseInterface
{
$csp = CSPBuilder::fromFile(config_path('csp.json'));
$response = $next($request);
$csp->injectCSPHeader($response);
return $response;
}
}
AppServiceProvider for global CSP headers:
public function boot()
{
$csp = CSPBuilder::fromFile(config_path('csp.json'));
$this->app->singleton(CSPBuilder::class, fn() => $csp);
}
Cache::remember) may need careful handling to avoid stale headers./csp-report). Laravel’s route system can handle this, but the endpoint must be secured (e.g., rate-limited, authenticated).Str::random() for nonces or disable caching for CSP-sensitive routes.unsafe-inline) may break legacy integrations (e.g., old jQuery plugins). Solution: Use report-only mode during testing.config/csp.json) or dynamic (modified per request/route)?unsafe-inline or unsafe-eval? If so, a gradual rollout with report-only is recommended.saveSnippet().app/Http/Kernel.php).CSPBuilder instance for reusable configurations.<script nonce="{{ $csp->nonce('script-src') }}">
// Dynamic JS
</script>
Illuminate\Http\Response).config/csp.json (e.g., block inline scripts by default).// app/Http/Middleware/CSPMiddleware.php
public function handle($request, \Closure $next)
{
$csp = app(CSPBuilder::class);
$response = $next($request);
$csp->injectCSPHeader($response);
return $response;
}
$csp->addSource('script-src', asset('js/admin.js'));
Route::middleware(['csp.admin'])->group(function () {
// Admin panel routes with relaxed CSP
});
routes/web.php):
Route::post('/csp-report', [CSPReportController::class, 'store']);
v2.x of the package.laravel/framework, guzzlehttp/psr7).composer require paragonie/csp-builder./csp-report).app/Http/Kernel.php.config/csp.json with a strict baseline policy.report-only mode to capture violations before enforcing.Str::random() for nonces to avoid collisions.report-only to identify gaps.upgrade-insecure-requests is enabled.report-uri endpoint is accessible.How can I help you explore Laravel packages today?