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, firewalls, user providers, and access control. Part of the main Symfony repository with established contribution and issue workflows.

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:
            Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        firewalls:
            main:
                lazy: true
                provider: app_user_provider
                form_login: ~
                logout: ~
        providers:
            app_user_provider:
                entity:
                    class: App\Entity\User
                    property: email
    
  3. First Use Case:

    • Create a User entity with UserInterface and PasswordAuthenticatedUserInterface.
    • Secure a route with annotations:
      use Symfony\Component\Security\Http\Attribute\IsGranted;
      
      #[IsGranted('ROLE_USER')]
      public function secureAction(): Response { ... }
      

Implementation Patterns

Authentication Workflows

  1. Form Login:

    firewalls:
        main:
            form_login:
                login_path: app_login
                check_path: app_login_check
                enable_csrf: true
    
    • Extend AbstractAuthenticator for custom logic:
      use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
      
      class CustomAuthenticator extends AbstractAuthenticator { ... }
      
  2. OAuth/OIDC:

    firewalls:
        main:
            oauth:
                resource_owners:
                    github: { client_id: ..., client_secret: ..., scope: "user:email" }
    
    • Use security:oidc-token:generate CLI command for testing.
  3. Remember-Me:

    firewalls:
        main:
            remember_me:
                secret: '%kernel.secret%'
                lifetime: 86400
                path: /
    

Authorization Patterns

  1. Role-Based Access:

    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
    
    • Use #[IsGranted] in controllers or access_decision() in Twig:
      {% if is_granted('ROLE_ADMIN') %} ... {% endif %}
      
  2. Voter Integration:

    use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
    
    class CustomVoter implements VoterInterface { ... }
    
    • Register in security.yaml:
      security:
          access_decision_manager:
              strategy: unanimous
          voters:
              - App\Security\CustomVoter
      
  3. Dynamic Roles:

    use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
    
    $token = $this->tokenStorage->getToken();
    $roles = $token->getRoleNames();
    

Common Integrations

  1. API Tokens:

    firewalls:
        api:
            pattern: ^/api
            stateless: true
            jwt: ~
    
    • Use lexik/jwt-authentication-bundle for JWT.
  2. Rate Limiting:

    security:
        firewalls:
            main:
                login_throttling:
                    max_attempts: 5
                    interval: 3600
    
  3. CSRF Protection:

    firewalls:
        main:
            csrf_protection: ~
    

Gotchas and Tips

Debugging

  1. Profiler:

    • Use the Symfony Profiler to inspect authentication events (_profiler/security).
    • Common issues: "ERROR" instead of "DENIED" (fixed in v8.0.8+).
  2. Lazy Firewalls:

    • Avoid remember_me on POST requests to public routes (fixed in v8.0.6+).
    • Debug with:
      bin/console debug:security
      
  3. Token Storage:

    • Reset adapters manually if needed (resettable since v8.0.8):
      $this->container->get('security.token_storage')->setToken(null);
      

Configuration Quirks

  1. Deprecations:

    • Remove hide_user_not_found (v7.4+).
    • Avoid XML config (deprecated in v7.4+).
    • Use #[IsGranted] instead of callable voters (deprecated in v8.0+).
  2. OIDC/OAuth:

    • Cache TTL for JWKS is now configurable via provider headers (v8.0+).
    • Use security:oidc-token:generate for testing:
      bin/console security:oidc-token:generate --endpoint="https://your-provider.com/.well-known/openid-configuration"
      
  3. Role Hierarchy:

    • Visualize with:
      bin/console debug:security role-hierarchy
      
    • Or dump as Mermaid (v7.4+):
      bin/console debug:security role-hierarchy --format=mermaid
      

Extension Points

  1. Custom Authenticators:

    • Implement AuthenticatorInterface for reusable logic.
    • Example: AbstractAuthenticator for form-based auth.
  2. Event Listeners:

    • Subscribe to SecurityEvents:
      use Symfony\Component\Security\Http\Event\AuthenticatorFailureEvent;
      
      $dispatcher->addListener(SecurityEvents::AUTHENTICATION_FAILURE, function (AuthenticatorFailureEvent $event) { ... });
      
  3. User Providers:

    • Extend UserProviderInterface for custom user loading:
      class CustomUserProvider implements UserProviderInterface { ... }
      
    • Register in security.yaml:
      providers:
          custom:
              id: App\Security\CustomUserProvider
      

Performance Tips

  1. Caching:

    • Cache role hierarchy and voter decisions:
      security:
          access_decision_manager:
              cache: app.cache.security
      
  2. Lazy Loading:

    • Use lazy: true in firewalls to defer authentication until first request.
  3. Token Storage:

    • Avoid frequent getToken() calls; store in a variable if reused.

Common Pitfalls

  1. CSRF Tokens:

    • Ensure enable_csrf: true for form logins to prevent CSRF attacks.
  2. Session Fixation:

    • Regenerate session IDs on login:
      security:
          session_fixation_strategy: new_session
      
  3. Role Conflicts:

    • Use unanimous strategy for strict access control:
      security:
          access_decision_manager:
              strategy: unanimous
      
  4. OIDC Discovery:

    • Validate discovery endpoints manually if using multiple providers (v8.0+).
  5. Deprecated Methods:

    • Avoid eraseCredentials() (removed in v7.3+); use PasswordAuthenticatedUserInterface instead.
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
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
twbs/bootstrap4