jenryollivierre / laranonce
为您的 Laravel 应用程序生成 nonce。
This package is auto-updated.
Last update: 2024-09-18 05:49:29 UTC
README
关于
Laranonce 是为 Laravel 应用程序生成的 nonce。
安装
使用 composer 命令 composer require jenryollivierre/laranonce
安装。
配置
在开始使用包之前,通过发布包的配置文件来配置选项。使用 artisan 命令 php artisan vendor:publish --tag=laranonce-config
。
配置选项
-
enabled:是否启用 nonce 功能。如果设置为 false,则所有 nonce 检查都将通过为真。这在测试应用程序时禁用 nonce 检查特别有用。默认为 true。
-
algorithm:生成 nonce 时使用的散列算法。默认为 'sha256'。请参阅 https://php.ac.cn/manual/en/function.hash-algos.php
-
lifetime:nonce 有效的秒数。默认为 900 秒(15 分钟)。
-
secret:nonce 生成过程中使用的密钥。这不应是公钥。理想情况下,您应该从 .env 文件中引用此值。默认为 App_Key .env 值。
-
driver:用于 nonce 进程的驱动程序。支持的驱动程序是数据库和文件。文件驱动程序建议使用,因为它比数据库驱动程序快两倍。默认为文件。
-
table_name:如果使用数据库驱动程序,要创建的表的名称。
-
storage_disk:使用文件驱动程序时,存储 nonce 的存储磁盘。永远不要使用公共磁盘!默认为 local。
-
storage_directory:使用文件驱动程序时,存储 nonce 的存储磁盘中的目录。默认为 nonces。
如何使用
在您的表单输入字段中,调用 Laranonce\Facades\Nonce::generate()
方法,该方法接受一个参数,即 nonce 的标识符。尽量使名称尽可能唯一,例如 Laranonce\Facades\Nonce::generate('submit_cart_paypal_payment');
<input type="hidden" name="nonce" value="{{ Laranonce\Facades\Nonce::generate('submit_cart_paypal_payment') }}">
然后在后端,您可以通过使用 Laranonce\Facades\Nonce::verify($name, $nonce)
方法进行检查,该方法接受两个参数。第一个参数是 nonce 操作的名称,第二个参数是与请求一起提交的 nonce 值
<?php namespace App\Http\Controllers\CartController; use Illuminate\Http\Request; use Laranonce\Facades\Nonce; class CartController extends Controller { public function __invoke(Request $request) { $nonce = $request->nonce; if (! Nonce::verify('submit_cart_paypal_payment', $nonce)) { // handle failed next action } } }
别名
在您的应用程序配置文件 config/app.php 中,您可以设置用于在视图文件中使用的别名。
'Nonce' => Laranonce\Facades\Nonce::class,
清理
为了使包成为一个真正的 nonce 包,数据将根据选择的驱动程序存储在数据库或文件存储中。要清理这些文件,请利用 Laravel 任务计划。请参阅 任务计划文档。
您可以通过调用 php artisan nonce:prune
命令来清理这些文件,该命令默认删除所有已过期的 nonce。您可以通过提供 'all' 参数来删除所有 nonce php artisan nonce:prune all
。
在您的任务计划中
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // Frequency determined based on expiration time set in config file $schedule->command('nonce:prune')->everyHour(); }