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

symfony/security

Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation Add via Composer (Laravel already includes Symfony Security components via laravel/framework):

    composer require symfony/security-bundle
    

    (Note: Laravel’s built-in auth scaffolding uses Symfony Security under the hood, so this is often pre-configured.)

  2. First Use Case: Basic Authentication

    • Use Laravel’s auth() helper or Auth facade to check authentication:
      if (auth()->check()) {
          $user = auth()->user();
      }
      
    • Protect routes with middleware:
      Route::middleware(['auth'])->group(function () {
          Route::get('/dashboard', [DashboardController::class, 'index']);
      });
      
  3. Where to Look First

    • Laravel Docs: Authentication (uses Symfony Security).
    • Symfony Docs: Security Component (for advanced use cases).
    • Laravel’s app/Http/Middleware/Authenticate.php: Core middleware leveraging Symfony’s AuthenticationProviderManager.

Implementation Patterns

1. Authentication Workflows

  • Guard Integration: Laravel’s Auth facade uses Symfony’s Guard system. Extend guards for custom logic:
    // app/Providers/AuthServiceProvider.php
    protected function guards()
    {
        return [
            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],
            'api' => [
                'driver' => 'token', // Uses Symfony’s TokenGuard
                'provider' => 'users',
            ],
        ];
    }
    
  • Custom User Providers: Implement Symfony\Component\Security\Core\User\UserProviderInterface:
    class CustomUserProvider implements UserProviderInterface {
        public function loadUserByIdentifier($identifier) {
            return User::where('email', $identifier)->firstOrFail();
        }
        // ... other required methods
    }
    

2. Authorization (Access Control)

  • Voters: Use Symfony’s Voter interface for granular permissions:
    use Symfony\Component\Security\Core\Authorization\Voter\Voter;
    
    class PostVoter extends Voter {
        protected function supports(string $attribute, $subject): bool {
            return $attribute === 'EDIT';
        }
        protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool {
            return $token->getUser()->id === $subject->user_id;
        }
    }
    
  • Register Voters:
    // app/Providers/AuthServiceProvider.php
    protected $policies = [
        Post::class => PostPolicy::class,
    ];
    
    (Laravel’s Policy class extends Symfony’s Voter.)

3. Session Management

  • Custom Session Strategies: Extend Symfony’s SessionAuthenticationStrategyInterface for stateless APIs or custom session handling.
  • Firewall Configuration: Define entry points (e.g., form_login, http_basic) in Laravel’s app/Http/Kernel.php or via middleware.

4. CSRF Protection

  • Laravel’s @csrf directive uses Symfony’s CsrfTokenManager. Override token generation in app/Providers/AppServiceProvider:
    public function register()
    {
        $this->app->singleton(Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class, function () {
            return new CustomCsrfTokenManager();
        });
    }
    

5. Event Listeners

  • Leverage Symfony’s security events (e.g., InteractiveLoginEvent, AuthenticationSuccessEvent) via Laravel’s event system:
    // app/Listeners/LogSuccessfulLogin.php
    public function handle(AuthenticationSuccessEvent $event) {
        Log::info('User logged in', ['user' => $event->getUser()]);
    }
    
    Register in EventServiceProvider.

Gotchas and Tips

Pitfalls

  1. Session Fixation

    • Ensure session.regenerate() is called after login (Laravel’s AuthenticatesUsers trait handles this by default).
    • Symfony’s AlwaysStoreSessionInterface can help enforce this.
  2. Token Expiry in Stateless APIs

    • For token-based auth (e.g., Sanctum), manually invalidate tokens in User model:
      public function tokens()
      {
          return $this->hasMany(Spatie\LaravelPermission\Models\Token::class);
      }
      
    • Use Symfony’s TokenStorage to clear tokens on logout.
  3. Circular Dependencies in Voters

    • Avoid loading the same entity multiple times in Voter::vote(). Cache results or use DTOs.
  4. Middleware Order Matters

    • Place auth middleware before throttle or custom middleware that might short-circuit requests.

Debugging Tips

  • Enable Symfony’s Security Debug Tool:

    // config/app.php
    'providers' => [
        Symfony\Bundle\DebugBundle\DebugBundle::class,
    ],
    

    (Adds a security tab in Laravel Debugbar.)

  • Log Authentication Events:

    // config/logging.php
    'channels' => [
        'security' => [
            'driver' => 'single',
            'path' => storage_path('logs/security.log'),
            'level' => 'debug',
        ],
    ],
    

    Then log events in listeners.

  • Dump Token Data:

    dd(auth()->user(), auth()->token(), auth()->getLastAttempted());
    

Extension Points

  1. Custom Authentication Providers

    • Implement Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface for OAuth, LDAP, or custom backends.
  2. Firewall Layers

    • Define multiple firewalls (e.g., main, api) in app/Http/Kernel.php:
      protected $middlewareGroups = [
          'web' => [
              // ...
              \App\Http\Middleware\TrustProxies::class,
              \Illuminate\Session\Middleware\AuthenticateSession::class,
              \Symfony\Component\Security\Http\Firewall::class, // Symfony Firewall
          ],
      ];
      
  3. Password Reset with Symfony’s UserCheckerInterface

    • Extend Symfony\Component\Security\Core\User\UserChecker to validate users before password changes:
      class CustomUserChecker implements UserCheckerInterface {
          public function checkPreAuth(UserInterface $user) {
              if (!$user->isActive()) {
                  throw new DisabledException('User account is disabled.');
              }
          }
      }
      
  4. Two-Factor Authentication (2FA)

    • Use Symfony’s TwoFactorAuthenticatorInterface or integrate with Laravel’s laravel-2fa package (which uses Symfony’s components).

Config Quirks

  • Session Storage: Laravel’s file/database session drivers work with Symfony Security, but redis requires additional config:
    // config/session.php
    'driver' => 'redis',
    'connection' => 'cache',
    
  • CSRF Domain: Set SESSION_DOMAIN in .env to match Symfony’s SameSite cookie policies:
    SESSION_DOMAIN=.yourdomain.com
    

Performance

  • Lazy-Load User Providers: Use Symfony\Component\Security\Core\User\UserProviderInterface::refreshUser() to avoid loading users unnecessarily.
  • Cache Voters: Decorate voters to cache authorization decisions:
    class CachedVoterDecorator implements VoterInterface {
        private $decorated;
        private $cache;
    
        public function vote(TokenInterface $token, $object, array $attributes) {
            $cacheKey = md5($token->getUser().serialize($object).$attributes[0]);
            if ($this->cache->has($cacheKey)) {
                return $this->cache->get($cacheKey);
            }
            $result = $this->decorated->vote($token, $object, $attributes);
            $this->cache->put($cacheKey, $result, 3600);
            return $result;
        }
    }
    
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