Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Csrf Route Bundle Laravel Package

genedys/csrf-route-bundle

A Laravel/PHP package for adding CSRF protection to routes, helping secure state-changing requests with token validation and straightforward route integration. Lightweight and simple to configure for safer forms and endpoints.

View on GitHub
Deep Wiki
Context7

Getting Started

Still calibrate expectations: genedys/csrf-route-bundle is a Symfony 3 bundle, not a Laravel package — and 3.0.0 does not change that. There is still no service provider, no facade, no config/csrf-route.php. What 3.0.0 does change is that the bundle has been modernized enough to be viable on Symfony 3.3/3.4 (the LTS) with PSR-4 autoloading and a fixed router performance problem. If you were previously told to avoid it because it was slow on large route sets, that specific objection is now resolved.

Minimal steps in a Symfony 3.3+ app:

composer require genedys/csrf-route-bundle:^3.0
// app/AppKernel.php
$bundles = [
    // ...
    new Genedys\CsrfRouteBundle\GenedysCsrfRouteBundle(),
];

Then look first at these places in vendor/genedys/csrf-route-bundle/src/ (note the PSR-4 src/ layout — 2.x used PSR-0, so paths moved):

  1. DependencyInjection/ — which services are registered. CsrfTokenManager no longer exists; token generation/storage logic was redistributed into other classes. Find the replacement service before you write any custom code.
  2. Routing/ — CsrfRouter no longer extends Symfony's Router. It is now a composition/decorator around the router, which is what killed the getRouteCollection performance hit. Verify how it is wired and whether it replaces or wraps router.
  3. The listener (EventListener/ or EventSubscriber/) — the kernel event and priority where tokens are validated.
  4. The annotation/attribute class (e.g. @CsrfToken) — how a route opts in. (3.0.0 stripped many class/method descriptions, so expect less inline documentation than 2.x.)

First use case: tag a single POST route as CSRF-protected, submit without a token, and confirm a 403 arrives before the controller runs. Then submit twice with the same token to confirm single-use/replay behavior. That tells you both the listener priority and the token lifecycle.

Laravel mental model is unchanged: roughly VerifyCsrfToken, but opt-in per route via annotation/route default instead of a global middleware group.

Implementation Patterns

Route-scoped protection (the core idea). Unchanged from 2.x at the API surface — annotate individual routes:

/**
 * @Route("/account/email", name="account_email", methods={"POST"})
 * @CsrfToken
 */
public function updateEmailAction(Request $request) { /* ... */ }

Laravel equivalent is still opt-in middleware:

Route::post('/account/email', ...)->middleware('csrf');

Router decoration, not inheritance (new in 3.0). Because CsrfRouter no longer extends Symfony\Component\Routing\Router, anything that type-hinted Router and expected the CSRF router to satisfy it will fail. Inject the CSRF-aware router where you need token-aware URL/route resolution, and the base router elsewhere. In Laravel terms: this is the difference between subclassing Illuminate\Routing\Router and wrapping it in a decorator — cleaner, faster, but a BC break for type hints.

Token identity per form/route. The genuinely useful pattern to steal: namespace tokens by route name or a configurable token id so a token minted for /checkout cannot be replayed against /admin/delete. Laravel's default token is session-global; for per-form tokens, implement a TokenManager salting with the route name plus a TTL and validate in custom middleware.

Listener and token services as the extension points. Everything interesting still happens on a kernel event (kernel.request for validation, possibly kernel.response for injection). To change where the token is read — X-CSRF-Token header for AJAX, body field for forms — override the token-extraction service in services.yml. Do not reach for CsrfTokenManager any more; that service was removed in 3.0.0 and any service definition referencing it will break container compilation.

Performance-sensitive setups get a second look. If your app has hundreds of routes and you dismissed this bundle in 2.x due to getRouteCollection overhead on every request, 3.0.0 is the release that makes it tolerable. Still benchmark before adopting — the fix removes one known cost, it does not make the bundle free.

Hybrid-stack tip (unchanged). If a Laravel API gateway fronts a Symfony 3 legacy app, do not share this bundle's session tokens across the boundary. Keep CSRF enforcement in the app that owns the session; the gateway uses stateless auth.

Gotchas and Tips

  • Still not a Laravel package. No laravel/framework constraint, no auto-discovery. composer require in Laravel succeeds and the code sits inert.
  • 3.0.0 is a bundle of breaking changes — treat the upgrade as a migration, not a patch:
    • CsrfTokenManager removed; logic moved to other classes. Any custom service definition, compiler pass, or direct $container->get('...csrf_token_manager') call breaks.
    • CsrfRouter no longer extends Symfony's Router. Type hints against Router/RouterInterface that assumed this class breaks.
    • PSR-0 → PSR-4: file paths moved (src/ layout), so any hardcoded vendor/... requires, classmap hack, or custom autoloader breaks. Run composer dump-autoload after upgrading.
    • Legacy Symfony < 2.4 compatibility code removed, and constraints raised to Symfony >= 3.3, PHP >= 5.5.9. You cannot upgrade on Symfony 3.0–3.2 or on PHP 5.4.
  • Still capped at Symfony 3.x / PHP 5.5.9+. No Symfony 4+/Flex support, no PHP 8 type-safety story. If you're on Symfony 4 or later, this bundle is unusable regardless of version — use Symfony's own CsrfTokenManager.
  • getRouteCollection performance fix is the headline. On route-heavy apps, 2.x rebuilt/iterated the route collection wastefully per request. If you previously profiled this bundle and rejected it, re-benchmark 3.0.0 rather than reusing the old objection.
  • Fewer inline docs. 3.0.0 explicitly removed "class/method descriptions." Read Configuration.php and the DI extension rather than relying on docblocks or README — 2017-era bundle docs drifted from code, and this release made the source quieter still.
  • Redundant with Symfony's own CSRF. The Form component and CsrfTokenManager already handle tokens. Check whether routes are already protected before adopting — double validation produces confusing 403s.
  • Session dependence (unchanged). Tokens live in the session; stateless: true firewalls and API endpoints will fail validation or silently mint new tokens. This is the most common source of "invalid CSRF token" in mixed apps.
  • Debugging 403s: (1) confirm the listener is registered and its priority precedes your controller firewall; (2) confirm the session started on the request; (3) dump the matched route's _csrf default/annotation to verify opt-in; (4) check the token field name — a mismatch between Twig rendering and listener extraction looks exactly like a routing bug; (5) after upgrading, confirm the container compiled cleanly, since a stale CsrfTokenManager reference fails only at runtime on some setups.
  • Extension points worth knowing: the replacement token generation/storage services (post-CsrfTokenManager), the token-extraction service, the annotation reader, and the (now non-inheriting) CsrfRouter. Override via service definition rather than forking.
  • Bottom line for a Laravel dev: still don't adopt it. But the upgrade is worth skimming again — 3.0.0 is a legitimate modernization (PSR-4, removed dead code, fixed the perf trap), which makes it a better reference implementation for route-keyed CSRF than it was. Read the new token services and the decorator-based router, then reimplement as ~40 lines of middleware with a Cache/session-backed TokenManager: same opt-in semantics, current PHP support, something you can debug.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package