fixed nonce
This commit is contained in:
parent
f5664ce84b
commit
6c589a20eb
3 changed files with 62 additions and 1 deletions
46
app/Http/Middleware/AddContentSecurityPolicy.php
Normal file
46
app/Http/Middleware/AddContentSecurityPolicy.php
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class AddContentSecurityPolicy
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
// Generate a random nonce for this request
|
||||
$nonce = base64_encode(random_bytes(16));
|
||||
|
||||
// Store nonce in request attributes so Livewire can access it
|
||||
$request->attributes->set('csp-nonce', $nonce);
|
||||
|
||||
// Get the response
|
||||
$response = $next($request);
|
||||
|
||||
// Build CSP header
|
||||
if (app()->environment('local')) {
|
||||
// Relaxed CSP for local development with Vite
|
||||
$csp = "script-src 'self' 'unsafe-inline' 'unsafe-eval' http: https:; " .
|
||||
"style-src 'self' 'unsafe-inline' http: https:; " .
|
||||
"connect-src 'self' ws: http: https:;";
|
||||
} else {
|
||||
// Strict CSP for production with nonces
|
||||
$scriptSrc = "'self' 'nonce-{$nonce}' https:";
|
||||
$styleSrc = "'self' 'unsafe-inline' https:";
|
||||
$connectSrc = "'self' https:";
|
||||
|
||||
$csp = "script-src {$scriptSrc}; style-src {$styleSrc}; connect-src {$connectSrc};";
|
||||
}
|
||||
|
||||
$response->headers->set('Content-Security-Policy', $csp);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
|
@ -11,7 +11,9 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
//
|
||||
$middleware->web(append: [
|
||||
\App\Http\Middleware\AddContentSecurityPolicy::class,
|
||||
]);
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
//
|
||||
|
|
|
|||
|
|
@ -170,4 +170,17 @@ return [
|
|||
*/
|
||||
|
||||
'pagination_theme' => 'tailwind',
|
||||
|
||||
/*
|
||||
|---------------------------------------------------------------------------
|
||||
| Content Security Policy Nonce
|
||||
|---------------------------------------------------------------------------
|
||||
|
|
||||
| When using Content-Security-Policy headers, Livewire can automatically
|
||||
| apply nonces to its injected scripts. Provide a closure that returns
|
||||
| the nonce value for the current request, or null to disable.
|
||||
|
|
||||
*/
|
||||
|
||||
'nonce' => fn () => request()->attributes->get('csp-nonce'),
|
||||
];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue