3

I'm currently working on a Laravel project that uses Telescope, Horizon, and Socialite. I've implemented a strict Content Security Policy (CSP) that disallows inline scripts, and I want to secure these packages by adding a nonce to any inline scripts they generate.

Problem: It still show "Refused to apply inline style because it violates the following Content Security Policy directive". I'm even try to staticly put the nonce like "private-nonce" but it still blocked

Environment: Laravel Version: 10.x Packages: Telescope, Horizon, Socialite CSP Implementation: Custom middleware for CSP header

What I've Tried: Adding Nonce in Blade Templates:

I’ve added a nonce to my own inline scripts and styles in Blade templates by generating a nonce in middleware and passing it to the views.

$nonce = base64_encode(random_bytes(16));
View::share('cspNonce', $nonce);

Then, im copying file from vendor to my resource folder , then I used the nonce in the templates like this: blade

<link 
    nonce="{{ $cspNonce }}"
    href="{{ asset(mix($cssFile, 'vendor/telescope')) }}" rel="stylesheet" type="text/css">
// some html code
<script nonce="{{ $cspNonce }}">
     window.Telescope = @json($telescopeScriptVariables);
</script>

Applying Nonce in CSP Header:

My CSP header includes the nonce:

$csp = "default-src 'self'; script-src 'self' 'nonce-$nonce';";

im stuck here for two days, any guidance or examples on how to achieve this would be greatly appreciated!

1 Answer 1

0

First step that you need to take is to look into your middleware code. Set the nonce in the handle function and pass through it using headers.

For Short Term Debugging purpose you can use unsafe-inline parameter in the set headers method in the middleware.

Furthermore you can try to use third party laravel-csp package

You can install this using

composer require spatie/laravel-csp

For more details see the documentation. https://github.com/spatie/laravel-csp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.