Weave Code
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

Security Csrf Laravel Package

symfony/security-csrf

Symfony Security CSRF component generates and validates CSRF tokens to protect forms and requests from cross-site request forgery. Provides CsrfTokenManager and related tools for secure token handling in Symfony and PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/security-csrf
    

    Ensure symfony/http-foundation is also installed (required for Request handling).

  2. Basic Setup:

    • For session-based CSRF (traditional Laravel apps):
      use Symfony\Component\Security\Csrf\CsrfTokenManager;
      use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
      use Symfony\Component\HttpFoundation\Session\SessionInterface;
      
      $session = app(SessionInterface::class);
      $tokenGenerator = new UriSafeTokenGenerator();
      $tokenManager = new CsrfTokenManager($tokenGenerator, $session);
      
    • For stateless CSRF (APIs/SPAs):
      use Symfony\Component\Security\Csrf\SameOriginCsrfTokenManager;
      use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
      
      $tokenGenerator = new UriSafeTokenGenerator();
      $tokenManager = new SameOriginCsrfTokenManager($tokenGenerator, 'X-CSRF-TOKEN');
      
  3. First Use Case: Generate a token for a form:

    $token = $tokenManager->getToken('form_action_name');
    echo '<input type="hidden" name="_csrf_token" value="' . $token . '">';
    

    Validate incoming requests:

    $requestToken = $request->request->get('_csrf_token');
    if (!$tokenManager->isTokenValid(new CsrfToken('form_action_name', $requestToken))) {
        abort(403, 'Invalid CSRF token');
    }
    
  4. Laravel Integration:

    • Create a service provider to bind the CsrfTokenManager:
      public function register()
      {
          $this->app->singleton(CsrfTokenManager::class, function ($app) {
              $session = $app->make(SessionInterface::class);
              $generator = new UriSafeTokenGenerator();
              return new CsrfTokenManager($generator, $session);
          });
      }
      
    • Use a custom middleware for validation:
      public function handle($request, Closure $next)
      {
          $tokenManager = app(CsrfTokenManager::class);
          $token = $request->input('_csrf_token');
          if (!$tokenManager->isTokenValid(new CsrfToken('global', $token))) {
              abort(403);
          }
          return $next($request);
      }
      

Implementation Patterns

Usage Patterns

  1. Token Generation:

    • Per-Action Tokens: Use unique IDs (e.g., delete_user_123) to scope tokens to specific actions.
      $token = $tokenManager->getToken('delete_user_' . $userId);
      
    • Global Tokens: Use a static ID (e.g., global) for broad protection.
      $token = $tokenManager->getToken('global');
      
  2. Validation Workflows:

    • Form Validation:
      $token = $request->input('_csrf_token');
      if (!$tokenManager->isTokenValid(new CsrfToken('form_submit', $token))) {
          throw new \RuntimeException('Invalid CSRF token');
      }
      
    • API Validation (stateless):
      $token = $request->headers->get('X-CSRF-TOKEN');
      if (!$tokenManager->isTokenValid(new CsrfToken('api_action', $token))) {
          abort(403);
      }
      
  3. Token Storage:

    • Session Storage (default):
      $tokenManager = new CsrfTokenManager($generator, $session);
      
    • Custom Storage (e.g., Redis):
      use Symfony\Component\Security\Csrf\Storage\SessionStorage;
      use Symfony\Component\Security\Csrf\Storage\StorageInterface;
      
      $storage = new SessionStorage($session);
      $tokenManager = new CsrfTokenManager($generator, $storage);
      
      For Redis:
      $storage = new RedisStorage($redisClient);
      
  4. Stateless APIs:

    • Use SameOriginCsrfTokenManager with headers/cookies:
      $tokenManager = new SameOriginCsrfTokenManager(
          $generator,
          'X-CSRF-TOKEN',
          ['Referer', 'Origin', 'Sec-Fetch-Site']
      );
      
    • Validate headers:
      $token = $request->headers->get('X-CSRF-TOKEN');
      if (!$tokenManager->isTokenValid(new CsrfToken('api_action', $token))) {
          abort(403);
      }
      

Workflows

  1. Laravel Middleware Integration:

    • Extend Laravel’s middleware to use Symfony’s token manager:
      public function handle($request, Closure $next)
      {
          $tokenManager = app(CsrfTokenManager::class);
          $token = $request->input('_csrf_token') ?? $request->headers->get('X-CSRF-TOKEN');
      
          if ($token && !$tokenManager->isTokenValid(new CsrfToken('global', $token))) {
              abort(403);
          }
          return $next($request);
      }
      
  2. Token in Templates:

    • Blade directive for forms:
      @csrf
      
      Create a directive in a service provider:
      Blade::directive('csrf', function () {
          $token = app(CsrfTokenManager::class)->getToken('global');
          return "<input type='hidden' name='_csrf_token' value='{$token}'>";
      });
      
  3. API Gateways:

    • Use SameOriginCsrfTokenManager for stateless validation:
      $tokenManager = new SameOriginCsrfTokenManager(
          $generator,
          'X-CSRF-TOKEN',
          ['Origin', 'Sec-Fetch-Site']
      );
      
    • Validate in a middleware:
      public function handle($request, Closure $next)
      {
          if ($request->is('api/*')) {
              $token = $request->headers->get('X-CSRF-TOKEN');
              if (!$tokenManager->isTokenValid(new CsrfToken('api', $token))) {
                  abort(403);
              }
          }
          return $next($request);
      }
      

Integration Tips

  1. Laravel Session Compatibility:

    • Symfony’s SessionInterface can work with Laravel’s session, but ensure the session is started:
      $session = app(SessionInterface::class);
      $session->start(); // Explicitly start if not auto-started
      
  2. Token Generator Customization:

    • Use UriSafeTokenGenerator for URL-safe tokens (default).
    • For custom generators (e.g., HMAC-based):
      use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
      
      $generator = new class implements TokenGeneratorInterface {
          public function generateToken(): string
          {
              return hash('sha256', uniqid(mt_rand(), true));
          }
      };
      
  3. Testing:

    • Mock CsrfTokenManager in tests:
      $tokenManager = $this->createMock(CsrfTokenManager::class);
      $tokenManager->method('isTokenValid')->willReturn(true);
      $this->app->instance(CsrfTokenManager::class, $tokenManager);
      
    • Test stateless validation:
      $request = new Request([], [], [], [], [], ['HTTP_X_CSRF_TOKEN' => $validToken]);
      $this->assertTrue($tokenManager->isTokenValid(new CsrfToken('api', $validToken)));
      
  4. Performance:

    • For high-traffic APIs, use stateless SameOriginCsrfTokenManager to avoid session overhead.
    • Cache token validation logic if tokens are regenerated frequently.

Gotchas and Tips

Pitfalls

  1. Session Dependency:

    • The default CsrfTokenManager requires a session. If the session isn’t started, tokens will fail to validate. Fix: Explicitly start the session or use SameOriginCsrfTokenManager for stateless apps.
  2. Token ID Collisions:

    • Using generic token IDs (e.g., global) may lead to collisions if not scoped properly. Fix: Use action-specific IDs (e.g., delete_user_123).
  3. Header Validation Quirks:

    • SameOriginCsrfTokenManager checks Referer, Origin, and Sec-Fetch-Site headers. Missing or malformed headers can cause false positives. Fix: Configure allowed headers explicitly:
      $tokenManager = new SameOriginCsrfTokenManager($generator, 'X-CSRF-TOKEN', ['Origin']);
      
  4. Double Validation:

    • Combining Laravel’s VerifyCsrfToken middleware with Symfony’s token manager can cause double validation
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport