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

Csrf Cookie Bundle Laravel Package

dneustadt/csrf-cookie-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dneustadt/csrf-cookie-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Dneustadt\CsrfCookieBundle\DneustadtCsrfCookieBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration: Override default settings in config/packages/dneustadt_csrf_cookie.yaml:

    dneustadt_csrf_cookie:
        enable: true
        name: XSRF-TOKEN  # Cookie name (must match client-side expectations)
    
  3. First Use Case:

    • Frontend (Axios Example):
      axios.get('/csrf-token'); // Triggers cookie generation
      axios.post('/api/endpoint', { data: '...' }, {
          headers: { 'X-XSRF-TOKEN': document.cookie.match(/XSRF-TOKEN=([^;]+)/)[1] }
      });
      
    • Symfony Route: Ensure your API routes extend csrf_token:
      # config/routes.yaml
      api_csrf_token:
          path: /csrf-token
          methods: [GET]
          defaults: { _controller: 'dneustadt_csrf_cookie.controller.csrf_token' }
      

Implementation Patterns

Workflow Integration

  1. Token Generation:

    • Expose /csrf-token route (or custom path via config) to fetch the token cookie.
    • Use HttpFoundation\Cookie to manually set cookies if needed:
      $response = new Response();
      $response->headers->setCookie(new Cookie('XSRF-TOKEN', $token, [
          'expires' => time() + 3600,
          'path' => '/',
          'secure' => true, // HTTPS only
      ]));
      
  2. Client-Side Handling:

    • Axios: Automatically includes X-XSRF-TOKEN header if cookie exists.
    • Fetch API: Manually extract token from cookies:
      const token = document.cookie.split('; ').find(row => row.startsWith('XSRF-TOKEN='))?.split('=')[1];
      fetch('/api/endpoint', { headers: { 'X-XSRF-TOKEN': token } });
      
  3. Symfony Controller:

    • Ensure CSRF_TOKEN is validated via Symfony’s built-in validator:
      #[Route('/api/endpoint', methods: ['POST'])]
      public function submit(Request $request): Response
      {
          $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
          $this->validateCsrfToken('csrf', $request->headers->get('X-XSRF-TOKEN'));
          // ...
      }
      
  4. Custom Routes:

    • Add multiple token routes (e.g., for SPAs):
      dneustadt_csrf_cookie:
          routes:
              - path: /api/csrf
                methods: [GET]
      

Integration Tips

  • SPA Frameworks: Use with React/Vue by pre-fetching the token during app initialization.
  • Testing: Mock cookies in PHPUnit:
    $client->getContainer()->get('request_stack')->getCurrentRequest()->headers->set('X-XSRF-TOKEN', 'valid_token');
    
  • CORS: Ensure Access-Control-Expose-Headers includes X-XSRF-TOKEN in preflight responses.

Gotchas and Tips

Pitfalls

  1. Cookie Scope:

    • secure: true requires HTTPS; test locally with secure: false or trusted_proxies config.
    • domain must match your site’s domain (e.g., .example.com for subdomains).
  2. Token Validation:

    • Symfony’s CSRF_TOKEN validator expects the token name to match config (name key).
    • For custom token names, override the validator:
      framework:
          csrf_token_generator:
              token_param: _csrf_token
      
  3. Axios Quirks:

    • Axios v0.21+ requires explicit withCredentials: true for cookies:
      axios.get('/csrf-token', { withCredentials: true });
      
  4. Double Submissions:

    • Ensure frontend doesn’t send both X-XSRF-TOKEN and _csrf_token (Symfony’s default).

Debugging

  • Missing Cookie:
    • Verify the /csrf-token route is hit (check Symfony logs).
    • Use browser dev tools (Application > Cookies) to confirm cookie presence.
  • Validation Failures:
    • Log the token from the request:
      error_log($request->headers->get('X-XSRF-TOKEN'));
      
    • Compare with the stored token (accessible via CsrfTokenManager).

Extension Points

  1. Custom Token Storage:
    • Override the CsrfTokenManager to use a database or cache:
      $tokenManager = new CustomTokenManager($container->get('security.csrf.token_manager'));
      $container->set('security.csrf.token_manager', $tokenManager);
      
  2. Dynamic Routes:
    • Extend the bundle’s CsrfTokenController to add logic (e.g., role-based token generation):
      public function csrfTokenAction(Request $request): Response
      {
          if (!$this->isGranted('ROLE_API_USER')) {
              throw $this->createAccessDeniedException();
          }
          return parent::csrfTokenAction($request);
      }
      
  3. Token Expiration:
    • Regenerate tokens on sensitive actions (e.g., login):
      $response = new Response();
      $response->headers->setCookie(new Cookie('XSRF-TOKEN', $newToken, ['expires' => time() + 300]));
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope