skip to Main Content

I’m facing an issue that the "nonce" value is always empty when using spatie/laravel-csp (v2.8.2) with vite and laravel framework (9.44). I followed the instructions on github page. Here is my configuration:

app/http/Kernel.php

protected $middlewareGroups = [
        'web' => [
            ...
            SpatieCspAddCspHeaders::class
        ],

config/csp.php

'nonce_generator' => AppSupportLaravelViteNonceGenerator::class,

The used policy uses the nonce directive from basic policy by spatie.

LaravelViteNonceGenerator.php

namespace AppSupport;

use IlluminateSupportStr;
use IlluminateSupportFacadesVite;
use SpatieCspNonceNonceGenerator;

class LaravelViteNonceGenerator implements NonceGenerator
{
    public function generate(): string
    {
        return Vite::useCspNonce();
    }
}

app.blade.php in my head

    @viteReactRefresh
    @vite('resources/js/app.jsx')

When I use @nonce directive, the nonce has the same random string value like shown in Content-Security-Policy header on my page but the script tag does not get it as attribute.

Some further information:
vite: 3.2.4
@vitejs/plugin-react: 2.2.0
laravel-vite-plugin: 0.6.1

What am i doing wrong?

2

Answers


  1. Chosen as BEST ANSWER

    Just in case somebody else is looking for this, I found a solution. The missing key is the csp_nonce() directive. So I created a meta tag with csp_nonce() directive like this:

    <meta property="csp-nonce" content="{{ csp_nonce() }}">
    

    After that, my vite-injected JS and CSS files got the nonce property and the browser did not block the content any more.


  2. Please be aware that the nonce attribute is stripped from the script element in Google Chrome. See Google Chrome Stripping nonce values from script tags for a more thorough answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search