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 Bundle Laravel Package

symfony/security-bundle

Symfony SecurityBundle integrates the Security component into the Symfony full-stack framework, providing authentication, authorization, and related security features with seamless configuration and framework tooling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/security-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration (config/packages/security.yaml):

    security:
        enable_authenticator_manager: true
        password_hashers:
            App\Entity\User: 'auto'
        firewalls:
            main:
                lazy: true
                provider: app_user_provider
                form_login:
                    login_path: app_login
                    check_path: app_login
                logout:
                    path: app_logout
        providers:
            app_user_provider:
                entity:
                    class: App\Entity\User
                    property: email
    
  3. First Use Case:

    • Create a User entity with UserInterface and PasswordAuthenticatedUserInterface.
    • Generate a login form controller:
      php bin/console make:auth
      
    • Secure a route with annotations:
      use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
      
      #[IsGranted('ROLE_USER')]
      public function secureAction(): Response { ... }
      

Key Files to Review

  • config/packages/security.yaml (main config)
  • src/Security/LoginFormAuthenticator.php (default authenticator)
  • src/Entity/User.php (user implementation)

Implementation Patterns

Authentication Workflows

  1. Form Login:

    • Use form_login under a firewall.
    • Customize with login_path, check_path, and csrf_token_generator.
    • Example:
      form_login:
          login_path: app_login
          check_path: app_login_check
          csrf_token_generator: security.csrf.token_manager
      
  2. API Token Authentication:

    • Use stateless: true and jwt or api_key authenticators.
    • Example:
      firewalls:
          api:
              pattern: ^/api
              stateless: true
              jwt: ~
      
  3. OAuth/OIDC:

    • Configure providers in security.yaml:
      oauth:
          providers:
              github:
                  client_id: '%env(GITHUB_CLIENT_ID)%'
                  client_secret: '%env(GITHUB_CLIENT_SECRET)%'
                  scope: 'read:user'
      firewalls:
          main:
              oauth: github
      

Role-Based Access Control (RBAC)

  • Define roles in security.yaml:
    role_hierarchy:
        ROLE_ADMIN: ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
    
  • Use in controllers:
    #[IsGranted('ROLE_ADMIN')]
    public function adminAction() { ... }
    
  • Twig Integration:
    {% if is_granted('ROLE_ADMIN') %}
        Admin Dashboard
    {% endif %}
    

Custom Authenticators

  1. Create a Custom Authenticator:

    php bin/console make:authenticator
    
    • Extend AbstractAuthenticator or AbstractFormLoginAuthenticator.
    • Override supports(), getCredentials(), getUser(), and checkCredentials().
  2. Register in security.yaml:

    firewalls:
        main:
            custom_authenticators:
                - App\Security\CustomAuthenticator
    

Firewall Strategies

  • Lazy Firewalls: Enable with lazy: true to defer authentication until needed.
  • Multiple Firewalls: Route based on patterns:
    firewalls:
        admin:
            pattern: ^/admin
            form_login: ~
        api:
            pattern: ^/api
            jwt: ~
    

Event Listeners

  • Listen to security events (e.g., AuthenticationSuccess, AccessDenied):
    use Symfony\Component\Security\Http\Event\AuthenticationSuccessEvent;
    
    public function onAuthenticationSuccess(AuthenticationSuccessEvent $event) {
        $user = $event->getUser();
        // Custom logic (e.g., log, redirect)
    }
    
  • Register in services.yaml:
    services:
        App\EventListener\SecurityListener:
            tags:
                - { name: kernel.event_listener, event: security.authentication.success, method: onAuthenticationSuccess }
    

Gotchas and Tips

Common Pitfalls

  1. CSRF Token Mismatches:

    • Ensure csrf_token_generator matches your form setup.
    • Debug with security.csrf.token_manager in the container.
  2. Lazy Firewall Issues:

    • Avoid mixing lazy: true with remember_me on public routes (fixed in v8.0.6).
    • Use context: main explicitly if needed:
      remember_me:
          context: main
      
  3. Role Hierarchy Conflicts:

    • Test hierarchies with:
      php bin/console debug:role-hierarchy
      
    • Use ROLE_ prefix consistently.
  4. OIDC/JWT Token Expiry:

    • Cache JWKS with security:oidc:jwks:cache (Symfony 8+).
    • Set TTL via provider headers (fixed in v8.0.0-RC2).
  5. Deprecated Features:

    • Avoid hide_user_not_found (removed in v7.4+).
    • Replace callable firewall listeners with service-based listeners.

Debugging Tips

  1. Profiler:

    • Enable security profiler data in config/packages/dev/security.yaml:
      security:
          profiler: true
      
    • Check the "Security" tab in the profiler for events and decisions.
  2. Logging:

    • Enable verbose logging in config/packages/dev/monolog.yaml:
      handlers:
          security:
              type: stream
              path: "%kernel.logs_dir%/security.log"
              level: debug
      
  3. Token Storage:

    • Reset the adapter for testing:
      $this->container->get('security.token_storage')->setToken(null);
      

Configuration Quirks

  1. XML Configuration:

    • Deprecated in Symfony 8+. Use YAML/PHP instead.
  2. Provider Factories:

    • Define without config (v8.0.11+):
      security:
          providers:
              custom_provider:
                  factory: [App\Security\UserProviderFactory, createUserProvider]
      
  3. Trusted Hosts for CAS:

    • Required for CAS authentication (v8.0.12+):
      framework:
          trusted_proxies: [192.168.0.1]
      

Extension Points

  1. Custom User Checker:

    • Implement UserCheckerInterface:
      public function checkPostAuth(UserInterface $user) { ... }
      
    • Register as a service with tags: ['security.user_checker'].
  2. Voter Extensions:

    • Create custom voters for fine-grained access control:
      use Symfony\Component\Security\Core\Authorization\Voter\Voter;
      
      class CustomVoter extends Voter { ... }
      
    • Tag in services.yaml:
      tags: ['security.voter']
      
  3. Rate Limiting:

    • Configure login throttling (v7.4+):
      security:
          firewalls:
              main:
                  login_throttling:
                      max_attempts: 5
                      interval: 3600
      
  4. Mermaid Role Hierarchy:

    • Generate a visual hierarchy (v7.4+):
      php bin/console debug:role-hierarchy --format=mermaid
      
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime