【问题标题】:Nonce is always empty when using spatie/laravel-csp with Laravel and vite.js在 Laravel 和 vite.js 中使用 spatie/laravel-csp 时,Nonce 总是空的
【发布时间】:2023-01-15 05:21:18
【问题描述】:

我面临一个问题,即在将 spatie/laravel-csp (v2.8.2) 与 vite 和 laravel 框架 (9.44) 一起使用时,“nonce”值始终为空。我按照 github 页面上的说明进行操作。这是我的配置:

应用程序/http/Kernel.php

protected $middlewareGroups = [
        'web' => [
            ...
            \Spatie\Csp\AddCspHeaders::class
        ],

配置/csp.php

'nonce_generator' => App\Support\LaravelViteNonceGenerator::class,

使用的策略使用 spatie 的基本策略中的 nonce 指令。

LaravelViteNonceGenerator.php

namespace App\Support;

use Illuminate\Support\Str;
use Illuminate\Support\Facades\Vite;
use Spatie\Csp\Nonce\NonceGenerator;

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

app.blade.php 在我脑海中

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

当我使用 @nonce 指令时,nonce 具有与我页面上的 Content-Security-Policy 标头中所示相同的随机字符串值,但脚本标记未将其作为属性获取。

一些进一步的信息: 邀请:3.2.4 @vitejs/插件反应:2.2.0 laravel-vite-插件:0.6.1

我究竟做错了什么?

【问题讨论】:

    标签: php reactjs vite content-security-policy laravel-9


    【解决方案1】:

    以防万一其他人正在寻找这个,我找到了解决方案。缺少的键是 @nonce 指令。所以我用 @nonce 指令创建了一个元标记,如下所示:

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

    之后,我的 vite 注入的 JS 和 CSS 文件获得了 nonce 属性,浏览器不再阻止内容。

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 2019-03-30
      • 2023-01-21
      • 1970-01-01
      • 2018-07-09
      相关资源
      最近更新 更多