Interview frequency: …
Short answer
Generate a unique random Nonce for each HTTP request, include it in the CSP header and in <script nonce="..."> tags to block injected scripts.
Explanation
CSP is a strong defense against advanced XSS attacks. With a Nonce, the browser refuses to run any script without the same random token as the header, even if an attacker manages to inject a <script> tag. Libraries such as spatie/laravel-csp provide integrated header management and automatically generate and share the Nonce with Blade templates.
Code example
<?php
// composer require spatie/laravel-csp (csp_nonce() comes from this package; it is not built into Laravel)
// app/Support/CspPolicy.php
namespace App\Support;
use Spatie\Csp\Directive;
use Spatie\Csp\Keyword;
use Spatie\Csp\Policies\Basic;
class CspPolicy extends Basic
{
public function configure()
{
parent::configure(); // Basic adds a per-request nonce to script-src and style-src
$this->addDirective(Directive::SCRIPT, Keyword::STRICT_DYNAMIC);
}
}
// config/csp.php → 'policy' => App\Support\CspPolicy::class
// bootstrap/app.php → $middleware->web(append: [\Spatie\Csp\AddCspHeaders::class]);
// resources/views/layout.blade.php
// <script nonce="{{ csp_nonce() }}">console.log("Allowed script");</script>
// Resulting header:
// Content-Security-Policy: script-src 'self' 'nonce-Xy7...' 'strict-dynamic'Common mistakes
- Using 'unsafe-inline' in a CSP header, which completely removes protection against XSS attacks.