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

Angular Csrf Bundle Laravel Package

dunglas/angular-csrf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dunglas/angular-csrf-bundle
    

    Add to config/bundles.php (Symfony 4+ auto-discovers, but ensure it's enabled):

    Dunglas\AngularCsrfBundle\DunglasAngularCsrfBundle::class => ['all' => true],
    
  2. Enable CSRF Token in Templates: Add this to your base template (e.g., base.html.twig):

    {{ csrf_token('angular_csrf') }}
    

    This injects a hidden <meta> tag with the CSRF token.

  3. AngularJS Service Integration: In your AngularJS app, inject the $http service and configure it to include the CSRF token:

    angular.module('myApp').config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.headers.common['X-CSRF-Token'] = angular.element('meta[name="csrf-token"]').attr('content');
    }]);
    
  4. Symfony Configuration: Ensure csrf_protection is enabled in config/packages/security.yaml:

    security:
        enable_authenticator_manager: true
        csrf_protection:
            enabled: true
    

First Use Case: Securing API Calls

For a simple AngularJS app making API calls to Symfony:

  1. Backend: Symfony routes (e.g., /api/users) will automatically validate the X-CSRF-Token header.
  2. Frontend: AngularJS $http requests will include the token via the configured header.

Implementation Patterns

Workflow: Token Injection

  1. Server-Side:

    • The bundle injects the CSRF token into responses via a <meta> tag (default) or a custom header (X-CSRF-Token).
    • Configure the token name in config/packages/dunglas_angular_csrf.yaml:
      dunglas_angular_csrf:
          token_name: 'X-CSRF-Token'  # Optional: Override default
      
  2. Client-Side:

    • AngularJS dynamically reads the token from the <meta> tag or uses a hardcoded value (not recommended).
    • For dynamic token refresh (e.g., after login), use a service:
      angular.module('myApp').factory('CsrfService', ['$http', function($http) {
          return {
              getToken: function() {
                  return angular.element('meta[name="csrf-token"]').attr('content');
              }
          };
      }]);
      

Integration Tips

  1. Symfony Forms: If using Symfony forms with AngularJS, ensure the form includes the CSRF token:

    {{ form_start(form, { attr: { 'data-csrf-token': csrf_token('angular_csrf') } }) }}
    
  2. API Platform: For API Platform, the bundle works out-of-the-box. No additional config is needed if using AngularJS clients.

  3. Non-AngularJS Clients: The bundle is framework-agnostic. For React/Vue, manually include the token in headers:

    // React example
    fetch('/api/endpoint', {
        headers: {
            'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
        }
    });
    
  4. Token Rotation: Regenerate the token on login/logout by clearing the <meta> tag and re-rendering the template:

    {% if app.user %}
        {{ csrf_token('angular_csrf') }}
    {% endif %}
    

Gotchas and Tips

Pitfalls

  1. Token Mismatch:

    • Issue: Token expires or changes (e.g., after login), causing 403 errors.
    • Fix: Refresh the token by reloading the <meta> tag or using a service to fetch a new one from /_csrf_token.
  2. CORS Issues:

    • Issue: If your AngularJS app runs on a different domain, CORS may block the X-CSRF-Token header.
    • Fix: Configure CORS in Symfony to allow the header:
      # config/packages/nelmio_cors.yaml
      nelmio_cors:
          defaults:
              allow_headers: ['X-CSRF-Token', 'Origin', 'Content-Type']
      
  3. Archived Status:

    • The bundle is archived and may not support newer Symfony versions. Test thoroughly or consider alternatives like DneustadtCsrfCookieBundle.
  4. Double Submissions:

    • Issue: Resubmitting a form (e.g., after a failed request) may cause CSRF validation to fail.
    • Fix: Disable the submit button after click or use AngularJS's $http interceptors to handle errors gracefully.

Debugging

  1. Check Headers: Use browser dev tools (Network tab) to verify the X-CSRF-Token header is sent with requests.

  2. Symfony Logs: Enable debug mode to see CSRF validation errors:

    # config/packages/dev/monolog.yaml
    monolog:
        handlers:
            main:
                level: debug
    
  3. Token Expiration: The token expires after each request. For long-lived sessions (e.g., WebSockets), regenerate it periodically.


Extension Points

  1. Custom Token Storage: Override the token storage mechanism by extending the bundle's TokenStorage service:

    // src/Service/CustomTokenStorage.php
    class CustomTokenStorage implements TokenStorageInterface {
        public function getToken(): string {
            return 'custom-token-value';
        }
    }
    

    Register it as a service in config/services.yaml:

    services:
        App\Service\CustomTokenStorage:
            tags: ['dunglas_angular_csrf.token_storage']
    
  2. Token Generation: Extend the TokenGenerator to use a custom strategy (e.g., UUID-based tokens):

    class CustomTokenGenerator implements TokenGeneratorInterface {
        public function generateToken(): string {
            return bin2hex(random_bytes(16));
        }
    }
    

    Bind it in config/services.yaml:

    services:
        App\Service\CustomTokenGenerator:
            tags: ['dunglas_angular_csrf.token_generator']
    
  3. Event Listeners: Listen to dunglas_angular_csrf.token_generated to log or modify tokens:

    // src/EventListener/CsrfTokenListener.php
    class CsrfTokenListener {
        public function onTokenGenerated(TokenGeneratedEvent $event) {
            // Custom logic here
        }
    }
    

    Register the listener:

    services:
        App\EventListener\CsrfTokenListener:
            tags:
                - { name: 'kernel.event_listener', event: 'dunglas_angular_csrf.token_generated' }
    
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.
facebook/capi-param-builder-php
babelqueue/symfony
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