You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel:如何程序化将路由加入VerifyCsrfToken的$except排除列表

Automatically Add Routes to VerifyCsrfToken's $except Array in Laravel

Great question! When building a package that handles payment webhooks, automating the CSRF exclusion for your routes is key to making the setup seamless for your users. Here are a few solid approaches you can take, ordered by how little they intrude on the user's project:

The cleanest way to avoid CSRF checks for your webhook routes is to skip the VerifyCsrfToken middleware directly when defining your package's routes. This requires zero changes to the user's existing VerifyCsrfToken class and keeps your package self-contained.

In your package's route file, use the withoutMiddleware method:

use Illuminate\Support\Facades\Route;
use YourPackageNamespace\Controllers\WebhookController;

Route::post('/your-package/webhook', [WebhookController::class, 'handle'])
    ->withoutMiddleware([\App\Http\Middleware\VerifyCsrfToken::class]);

Why this works:

  • Laravel allows you to exclude specific middleware for individual routes, so your webhook endpoint will bypass CSRF validation automatically when the package is installed.
  • No impact on the user's existing CSRF exclusion list or middleware setup.

2. Modify the VerifyCsrfToken Middleware's $except Property Programmatically

If you need to add your routes to the global $except array (for example, if your routes are registered dynamically), you can modify the middleware instance directly from your package's service provider.

In your package's service provider's boot method:

namespace YourPackageNamespace;

use Illuminate\Support\ServiceProvider;
use App\Http\Middleware\VerifyCsrfToken;

class YourPackageServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Fetch the existing VerifyCsrfToken instance from the container
        $csrfMiddleware = $this->app->make(VerifyCsrfToken::class);
        
        // Define your package's webhook routes to exclude
        $webhookRoutes = [
            '/your-package/webhook',
            // Add any additional routes here
        ];
        
        // Merge your routes with the existing $except array (avoid overwriting)
        $csrfMiddleware->except = array_merge($csrfMiddleware->except, $webhookRoutes);
    }
}

Notes:

  • This works because Laravel resolves the VerifyCsrfToken middleware from the container, so we can modify its properties at boot time.
  • It preserves any existing routes the user has already added to $except.

3. Use Config Merging (Requires User Cooperation)

If you prefer to follow Laravel's configuration patterns, you can encourage users to move their $except array to a config file, then merge your package's routes into that config.

Step 1: Ask users to update their VerifyCsrfToken class

Have them modify App\Http\Middleware\VerifyCsrfToken to pull the exclusion list from a config file:

class VerifyCsrfToken extends BaseVerifier
{
    protected $except = [];

    public function __construct()
    {
        // Load exclusions from config (fallback to empty array if not set)
        $this->except = config('csrf.except', []);
    }
}

Step 2: Merge your package's config in your service provider

In your package's service provider:

public function boot()
{
    // Merge your package's CSRF config with the user's config
    $this->mergeConfigFrom(
        __DIR__.'/../config/csrf.php', 'csrf'
    );

    // Optional: Publish the config file so users can override it
    $this->publishes([
        __DIR__.'/../config/csrf.php' => config_path('csrf.php'),
    ], 'your-package-config');
}

Step 3: Create your package's config file (config/csrf.php)

return [
    'except' => [
        '/your-package/webhook',
    ],
];

Why this approach:

  • It centralizes CSRF exclusions in a config file, which is more maintainable for users.
  • Users can easily override or add to the exclusion list if needed.
  • Downside: Requires users to modify their VerifyCsrfToken class, which adds a setup step.

内容的提问来源于stack exchange,提问作者arjayads

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:10:02