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

Symfony Security Bundle Laravel Package

cooolinho/symfony-security-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cooolinho/symfony-security-bundle
    

    Verify the package appears in composer.json under require.

  2. Configure .env Add SMTP credentials for password reset/email functionality:

    MAILER_DSN=smtp://user:pass@smtp.example.com:587
    
  3. Update security.yaml

    • Encoders: Register the User entity:
      security:
          encoders:
              App\Entity\User:  # Replace with your User class if different
                  algorithm: auto
      
    • Provider: Define a custom provider (e.g., app_user_provider):
      providers:
          app_user_provider:
              entity:
                  class: App\Entity\User  # Replace with your User class
                  property: email  # or 'username'
      
    • Firewall: Attach the bundle’s UserChecker and SecurityAuthenticator:
      firewalls:
          main:
              provider: app_user_provider
              user_checker: Cooolinho\Bundle\SecurityBundle\Security\UserChecker
              custom_authenticator:
                  - Cooolinho\Bundle\SecurityBundle\Security\SecurityAuthenticator
      
  4. Basic Role Hierarchy Define roles in security.yaml:

    role_hierarchy:
        ROLE_ADMIN: ROLE_USER
    
  5. Access Control Restrict routes:

    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
    
  6. Bundle Configuration Add cooolinho_security.yaml to config/packages/:

    cooolinho_security:
        # Minimal config (extend as needed)
        role_hierarchy: ~
    

First Use Case

Password Reset Flow:

  • Trigger a reset via /reset-password (if the bundle exposes this route).
  • Verify the UserChecker validates reset tokens (check Security\UserChecker for logic).
  • Use the SecurityAuthenticator to handle token-based authentication.

Implementation Patterns

Workflows

  1. Authentication

    • Custom Authenticator: Extend SecurityAuthenticator to add logic (e.g., 2FA, IP checks).
      use Cooolinho\Bundle\SecurityBundle\Security\SecurityAuthenticator as BaseAuthenticator;
      
      class CustomAuthenticator extends BaseAuthenticator {
          public function supports(Request $request) { ... }
          public function authenticate(TokenInterface $token) { ... }
      }
      
    • Register in security.yaml:
      custom_authenticator:
          - App\Security\CustomAuthenticator
      
  2. User Providers

    • Dynamic Properties: Use property: email or property: username in the provider to switch authentication fields.
    • Custom User Classes: Ensure your User entity implements Symfony\Component\Security\Core\User\UserInterface.
  3. Role-Based Access

    • Hierarchy: Leverage role_hierarchy to simplify role checks (e.g., ROLE_ADMIN inherits ROLE_USER).
    • Dynamic Roles: Use voters or access control lists (ACLs) for granular permissions beyond roles.
  4. Email Integration

    • Templates: Override email templates (e.g., reset_password.html.twig) in templates/cooolinho_security/.
    • Events: Listen for SecurityBundleEvents::PASSWORD_RESET to customize reset logic.

Integration Tips

  • Symfony Forms: Use the bundle’s UserType for registration/login forms:
    use Cooolinho\Bundle\SecurityBundle\Form\UserType;
    
    $builder->add('user', UserType::class);
    
  • Doctrine: Ensure your User entity has password and roles fields (standard Symfony security requirements).
  • Testing: Mock SecurityAuthenticator and UserChecker in PHPUnit tests:
    $this->container->set('security.user_checker', $mockChecker);
    

Gotchas and Tips

Pitfalls

  1. Missing Encoder Configuration

    • Error: Invalid password hash or Bad credentials.
    • Fix: Ensure the User entity’s password field uses algorithm: auto in security.yaml.
  2. Provider Mismatch

    • Error: User not found during login.
    • Fix: Verify the class and property in the provider match your User entity (e.g., property: email vs. username).
  3. Firewall Misconfiguration

    • Error: Authentication bypass or 403 errors.
    • Fix: Ensure the firewall’s provider matches the provider name in security.yaml.
  4. Role Hierarchy Overrides

    • Error: Roles not propagating as expected.
    • Fix: Use ROLE_ prefix consistently (e.g., ROLE_ADMIN, not admin).
  5. Email Delivery Failures

    • Error: Reset emails not sending.
    • Fix: Validate MAILER_DSN in .env and check SMTP server logs.

Debugging

  • Symfony Profiler: Use the security panel to inspect:
    • Authenticated user.
    • Granted roles.
    • Authentication attempts.
  • Logs: Enable debug mode (APP_DEBUG=true) and check var/log/dev.log for security events.
  • Token Dumps: Debug SecurityAuthenticator by dumping the TokenInterface:
    dump($token->getCredentials());
    

Extension Points

  1. Custom User Checker Extend UserChecker to add logic (e.g., account expiration):

    class CustomUserChecker extends \Cooolinho\Bundle\SecurityBundle\Security\UserChecker {
        public function checkPreAuth(UserInterface $user) {
            if ($user->isExpired()) {
                throw new AccountExpiredException();
            }
        }
    }
    

    Register in services.yaml:

    services:
        App\Security\CustomUserChecker:
            tags: [security.user_checker]
    
  2. Event Listeners Subscribe to bundle events (e.g., PASSWORD_RESET):

    use Cooolinho\Bundle\SecurityBundle\Event\SecurityEvents;
    
    $eventDispatcher->addListener(SecurityEvents::PASSWORD_RESET, function ($event) {
        // Custom logic (e.g., log reset, send SMS)
    });
    
  3. Override Templates Copy default templates from vendor/cooolinho/symfony-security-bundle/Resources/views/ to templates/cooolinho_security/ to customize:

    • login.html.twig
    • reset_password.html.twig
  4. Configuration Overrides Extend cooolinho_security.yaml:

    cooolinho_security:
        role_hierarchy:
            ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
        # Custom settings
        max_password_attempts: 5
    

Config Quirks

  • Algorithm Auto-Detection: If algorithm: auto fails, explicitly set algorithm: bcrypt or argon2i.
  • Case Sensitivity: Role names in access_control are case-sensitive (ROLE_ADMINrole_admin).
  • Provider Order: If using multiple providers, ensure the correct one is referenced in the firewall.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware