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

symfony/security-http

Symfony Security HTTP integrates the Security Core with HTTP: firewalls, authenticators, and request/response handling to protect parts of your app and authenticate users. Install via composer require symfony/security-http.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

To integrate symfony/security-http into a Laravel application, start by installing the package via Composer:

composer require symfony/security-http

First Use Case: Basic Authentication

  1. Configure Security Bundle (if not using Laravel's built-in auth): Laravel already integrates Symfony's security components, so you can leverage security-http directly in your config/auth.php or custom security configuration.

  2. Define a Firewall (e.g., in app/Providers/AuthServiceProvider.php):

    use Symfony\Component\HttpFoundation\RequestMatcher;
    use Symfony\Component\Security\Http\Firewall;
    
    public function boot()
    {
        $firewall = new Firewall(
            $this->createAuthenticator(),
            new RequestMatcher('/login', ['GET', 'POST'])
        );
        $firewall->addListener('authentication.failure', [$this, 'onAuthenticationFailure']);
        $this->app['security.firewall_map']->add('main', $firewall);
    }
    
  3. Create a Custom Authenticator (e.g., app/Services/CustomAuthenticator.php):

    use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
    use Symfony\Component\Security\Core\User\UserProviderInterface;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Security\Core\Exception\AuthenticationException;
    
    class CustomAuthenticator extends AbstractAuthenticator
    {
        public function supports(Request $request): ?bool
        {
            return $request->isMethod('POST') && $request->getPathInfo() === '/login';
        }
    
        public function authenticate(Request $request): Passport
        {
            $email = $request->request->get('email');
            $password = $request->request->get('password');
    
            if (null === $user = $this->userProvider->loadUserByIdentifier($email)) {
                throw new AuthenticationException('Invalid credentials.');
            }
    
            return new Passport(new UserPasswordCredentials($email, $password), new RememberMeCookie());
        }
    
        public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
        {
            return new RedirectResponse('/dashboard');
        }
    
        public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
        {
            return new RedirectResponse('/login?error=' . urlencode($exception->getMessage()));
        }
    }
    
  4. Register the Authenticator in AuthServiceProvider:

    protected function createAuthenticator()
    {
        return new CustomAuthenticator($this->app->make(UserProviderInterface::class));
    }
    

Key Starting Points

  • Documentation: Symfony Security Component
  • Laravel Integration: Leverage Laravel's existing auth facade or AuthenticatesUsers trait for simpler setups.
  • Common Authenticators: Use built-in authenticators like FormLoginAuthenticator, RememberMeAuthenticator, or OidcAuthenticator.

Implementation Patterns

Workflows

1. Authentication Flow

  • Request Handling: Use AbstractAuthenticator to handle login requests. Override supports(), authenticate(), and success/failure callbacks.
  • Token Management: Use TokenInterface (e.g., UsernamePasswordToken) to represent authenticated users.
  • Passport: Encapsulate credentials and tokens in a Passport object for secure transmission.

2. Authorization

  • Attributes: Use Symfony attributes like [IsGranted] for method-level authorization:
    #[IsGranted('ROLE_ADMIN')]
    public function adminDashboard(): Response
    {
        return new Response('Welcome, Admin!');
    }
    
  • Voters: Implement VoterInterface for custom authorization logic:
    class PostVoter implements VoterInterface
    {
        public function vote(AuthenticatedToken $token, mixed $subject, array $attributes): bool
        {
            return $token->getUser()->isOwnerOf($subject);
        }
    }
    

3. Firewalls and Matchers

  • Dynamic Firewalls: Use RequestMatcher to apply firewalls to specific routes or patterns:
    $matcher = new RequestMatcher('/admin', ['GET']);
    $firewall = new Firewall($authenticator, $matcher);
    
  • Multiple Firewalls: Combine firewalls for layered security (e.g., API vs. web).

4. Remember-Me and CSRF

  • Remember-Me: Enable via RememberMeAuthenticator:
    $firewall->addListener('remember_me', new RememberMeListener($this->rememberMeServices));
    
  • CSRF Protection: Use CsrfTokenManager for form protection:
    #[IsCsrfTokenValid('authenticate')]
    public function login(Request $request): Response
    {
        // Handle login
    }
    

5. OAuth/OIDC Integration

  • OIDC Authenticator: Configure OpenID Connect:
    $oidcAuthenticator = new OidcAuthenticator(
        $clientId,
        $clientSecret,
        $issuerUrl,
        $userProvider
    );
    $firewall->addListener('authentication', $oidcAuthenticator);
    

Integration Tips

  • Laravel-Specific: Use Laravel's Auth::attempt() alongside Symfony's UserProviderInterface for hybrid setups.
  • Middleware: Convert Symfony listeners (e.g., AuthenticationListener) to Laravel middleware for seamless integration.
  • Testing: Use AuthenticationUtils to test authentication flows:
    $utils = new AuthenticationUtils();
    $authenticationException = $utils->getLastAuthenticationError();
    

Gotchas and Tips

Pitfalls

  1. CSRF Bypass in HEAD Requests

    • Issue: HEAD requests may bypass #[IsCsrfTokenValid] checks (fixed in v8.0.12+).
    • Fix: Ensure your firewall includes CSRF protection for all methods or explicitly handle HEAD requests.
  2. Lazy User Serialization

    • Issue: Lazy-loaded users may fail during serialization (e.g., in remember-me cookies).
    • Fix: Initialize lazy properties before serialization or use UserInterface::getRoles() to trigger loading.
  3. Impersonation Quirks

    • Issue: Impersonation tokens may deauthenticate on every request (fixed in v8.0.11+).
    • Fix: Use ImpersonatingToken and ensure proper token persistence.
  4. OIDC Discovery with Multiple HttpClients

    • Issue: OIDC discovery may fail if multiple HttpClient instances are used.
    • Fix: Configure a single HttpClient for OIDC or use the security:oidc-token:generate command.
  5. Empty JSON Login Credentials

    • Issue: Empty JSON login credentials may not throw BadCredentialsException (fixed in v8.0.9+).
    • Fix: Validate credentials explicitly in custom authenticators.

Debugging Tips

  • Enable Security Events: Listen to events like security.authentication.failure for debugging:
    $this->app->make('event.dispatcher')->addListener(
        'security.authentication.failure',
        function (AuthenticationFailureEvent $event) {
            \Log::error('Auth failure: ' . $event->getException()->getMessage());
        }
    );
    
  • Check Firewall Order: Ensure firewalls are ordered correctly (e.g., API firewall before main firewall).
  • Token Inspection: Use TokenStorage to inspect the current user/token:
    $token = $this->app['security.token_storage']->getToken();
    \Log::info('Current user:', $token->getUser());
    

Configuration Quirks

  1. Trusted Hosts for CAS

    • Requirement: CAS authentication requires trusted_hosts configuration (enforced in v8.0.12+).
    • Fix: Set trusted_hosts: ['yourdomain.com'] in your CAS authenticator.
  2. Base URL Preservation

    • Issue: HttpUtils::createRequest() may strip base URLs (fixed in v8.0.11+).
    • Fix: Ensure your Context object includes the base URL.
  3. Deprecated Constructors

    • Issue: Legacy constructors (e.g., RememberMeDetails) are deprecated.
    • Fix: Use setters or updated constructors (e.g., RememberMeDetails::create()).

Extension Points

  1. Custom Authenticators

    • Extend AbstractAuthenticator or implement AuthenticatorInterface for bespoke flows (e.g., JWT, API keys).
  2. Voters and Access Control

    • Implement VoterInterface for granular permissions or override AccessDecisionManager.
  3. Token Providers

    • Create custom TokenProviderInterface implementations for stateless tokens (e.g., JWT).
  4. Event Listeners

    • Sub
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.
codraw/graphviz
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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