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 configuration for applications built with Symfony.

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: ~
        providers:
            app_user_provider:
                entity:
                    class: App\Entity\User
                    property: email
    
  3. First Use Case:

    • Protect a route with annotations:
      use Symfony\Component\Security\Http\Attribute\IsGranted;
      
      #[IsGranted('ROLE_USER')]
      public function secureAction(): Response
      {
          return new Response('Secure content');
      }
      
    • Test with php bin/console debug:security to inspect roles, users, and voters.

Implementation Patterns

Core Workflows

1. Authentication

  • Form Login:

    firewalls:
        main:
            form_login:
                login_path: app_login
                check_path: app_login_check
    
    • Use #[IsGranted('IS_AUTHENTICATED_FULLY')] to restrict routes.
  • OAuth/OIDC:

    firewalls:
        main:
            oauth:
                resource_owners:
                    github: { client_id: ..., client_secret: ..., provider: oauth_github }
    
    • Leverage security:oidc-token:generate CLI command for testing.

2. Authorization

  • Role-Based Access Control (RBAC):

    security:
        access_control:
            - { path: ^/admin, roles: ROLE_ADMIN }
    
    • Use #[IsGranted('ROLE_ADMIN')] in controllers or access_decision() in Twig.
  • Voters: Custom voter for complex logic:

    use Symfony\Component\Security\Core\Authentication\Voter\Voter;
    
    class PostVoter extends Voter {
        protected function supports(string $attribute, mixed $subject): bool {
            return $attribute === 'EDIT_POST' && $subject instanceof Post;
        }
    
        protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool {
            return $token->getUser() === $subject->getAuthor();
        }
    }
    

    Register in security.yaml:

    security:
        voters:
            - App\Security\PostVoter
    

3. Firewalls & Entry Points

  • Lazy Firewalls:

    firewalls:
        api:
            lazy: true
            provider: app_user_provider
            stateless: true
            json_login:
                check_path: /api/login_check
    
    • Useful for API routes to avoid loading security context on every request.
  • Custom Entry Points:

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

4. Remember-Me

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

5. Rate Limiting

security:
    rate_limiter:
        login:
            storage: memory
            policy: 10 per minute

Configure storage (e.g., Redis) in config/packages/security.yaml.


Integration Tips

  1. Symfony UX & Live Components: Use #[IsGranted] with Live Components to dynamically show/hide UI elements:

    #[IsGranted('ROLE_USER')]
    public function userPanel(LiveComponentInterface $component): Response
    {
        return $this->renderComponent($component, ['user' => $this->getUser()]);
    }
    
  2. Messenger Integration: Dispatch security events (e.g., AuthenticationSuccessEvent) via Messenger for async processing:

    use Symfony\Component\Security\Http\Event\AuthenticationSuccessEvent;
    
    public function onAuthenticationSuccess(AuthenticationSuccessEvent $event): void
    {
        $this->messageBus->dispatch(new UserLoggedIn($event->getUser()));
    }
    
  3. API Platform: Combine with API Platform’s security extensions for JWT/OAuth2:

    security:
        firewalls:
            api:
                pattern: ^/api
                stateless: true
                jwt: ~
    
  4. Testing: Use LoginLink for testing authenticated routes:

    use Symfony\Component\Security\Http\Authenticator\Passport\LoginLink;
    
    public function testSecureRoute(): void
    {
        $link = new LoginLink('https://example.com/login');
        $client->followRedirects(true);
        $client->request('GET', '/secure-route', [], [], ['HTTP_REFERER' => 'https://example.com']);
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecations:

    • Avoid eraseCredentials() in UserInterface (deprecated in Symfony 7.3+).
    • Replace XML config with PHP/YAML (fully deprecated in Symfony 8).
    • Callable firewall listeners are removed in Symfony 8; use classes instead.
  2. Role Hierarchy:

    • Circular dependencies in role hierarchy (e.g., ROLE_ADMINROLE_USERROLE_ADMIN) cause infinite loops. Use security:role-hierarchy:dump to visualize:
      php bin/console security:role-hierarchy:dump --format=mermaid
      
  3. Lazy Firewalls:

    • Lazy firewalls trigger authentication on the first request to a secured route. For APIs, ensure stateless: true to avoid session issues.
  4. OIDC/OAuth2:

    • Cache JWKS (JSON Web Key Set) to avoid repeated network calls:
      security:
          oauth:
              providers:
                  oidc:
                      jwks_uri: https://example.com/.well-known/jwks.json
                      cache: true
      
    • Use security:oidc-token:generate to debug token generation locally.
  5. Remember-Me:

    • Ensure secret is unique and stored securely (e.g., %kernel.secret%).
    • Test with COOKIE_USE_ONLY_HTTP_PATH=false in PHP to avoid local development issues.
  6. CSRF Protection:

    • Disable CSRF for non-idempotent API methods (e.g., POST):
      security:
          csrf_token_generator:
              enabled: true
          firewalls:
              main:
                  csrf_protection: ~
      
    • For APIs, use stateless: true and handle CSRF manually (e.g., with custom tokens).

Debugging Tips

  1. Profiler:

    • Use the Symfony Profiler to inspect:
      • Authentication attempts (_profiler/security).
      • Access decisions (_profiler/security/access_decision).
      • Voters (_profiler/security/voters).
  2. Logging:

    • Enable debug logging for security events:
      monolog:
          handlers:
              security:
                  type: stream
                  path: "%kernel.logs_dir%/security.log"
                  level: debug
                  channels: ["security"]
      
  3. CLI Commands:

    • Dump role hierarchy:
      php bin/console security:role-hierarchy:dump
      
    • List users:
      php bin/console debug:security:users
      
    • List voters:
      php bin/console debug:security:voter
      
  4. Common Errors:

    • "No authentication provider found": Ensure firewalls reference a valid provider in security.yaml.
    • "User not found": Check UserProvider implementation and property in entity provider.
    • CSRF Token Mismatch: Verify csrf_token is included in forms and csrf_protection is enabled.

Extension Points

  1. Custom Authenticators: Extend AbstractAuthenticator for custom logic (e.g., API keys, JWT):
    use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
    
    class ApiKeyAuthenticator extends AbstractAuthenticator {
        public function supports(Request $request): ?bool {
            return $request->headers->has('X-API-KEY');
        }
    
        public function authenticate(Request $request): Passport {
            $apiKey = $request->headers->get('X-API-KEY');
            return new ApiKeyPassport($apiKey);
        }
    }
    
    Register in security.yaml:
    security:
        firewalls:
            api:
                custom_authenticators:
                    - App\Security
    
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
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
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation