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 (Updated for v8.1.0-BETA3)
Install the updated package via Composer:
```bash
composer require symfony/security-http:^8.1.0-BETA3

First Use Case: Secure Routes with New Attribute Syntax

Leverage the updated attribute system (now hardened against HEAD request bypasses):

// routes/web.php
use Symfony\Component\Security\Http\Attribute\IsGranted;

Route::get('/admin', [AdminController::class, 'dashboard'])
    ->middleware(['auth'])
    ->withAttributes([
        new IsGranted('ROLE_ADMIN')
    ]);

Key Entry Points (Updated)

  1. app/Http/Kernel.php: Register middleware with security hardening:
    protected $middlewareGroups = [
        'web' => [
            \Symfony\Component\Security\Http\Middleware\FirewallMiddleware::class,
            // Other middleware...
        ],
    ];
    
  2. config/security.php: Updated OIDC configuration with new claim handling:
    'providers' => [
        'oidc' => [
            'type' => 'openid_connect',
            'claims' => ['email', 'name'], // Explicitly define claims (CVE-2026-45069 fix)
        ],
    ],
    
  3. Route Groups: Use middleware with updated attribute validation:
    Route::middleware(['auth', 'csrf'])->group(function () {
        // Protected routes with CSRF protection
    });
    

Implementation Patterns

1. Firewall Workflows (Updated)

  • New Security Requirement: Configure trusted hosts for CAS authentication:
    // config/security.php
    'firewalls' => [
        'cas' => [
            'pattern' => '^/cas',
            'cas' => [
                'service' => '/cas/service',
                'trusted_hosts' => ['yourdomain.com', 'localhost'], // Required for CAS (CVE-2026-45074)
            ],
        ],
    ],
    

2. OIDC Integration (Updated)

  • New Claim Handling: Explicitly define claims to avoid CVE-2026-45069:
    // config/security.php
    'providers' => [
        'oidc' => [
            'type' => 'openid_connect',
            'client_id' => 'your-client-id',
            'claims' => ['email', 'name', 'preferred_username'], // Explicit claims
            'discovery_endpoint' => 'https://your-identity-provider/.well-known/openid-configuration',
        ],
    ],
    
  • User Attribute Fetching:
    use Symfony\Component\Security\Core\User\UserInterface;
    
    #[CurrentUser]
    public function show(UserInterface $user)
    {
        // Access claims via $user->getUserIdentifier() or custom getters
        return view('profile', ['user' => $user]);
    }
    

3. CSRF Protection (Hardened)

  • New Attribute Syntax: Updated to prevent HEAD request bypasses:
    use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
    
    class ProfileController
    {
        #[IsCsrfTokenValid(
            token: 'profile_update',
            message: 'Invalid CSRF token.',
            methods: ['POST', 'PUT', 'PATCH'] // Explicitly define allowed methods
        )]
        public function update(Request $request)
        {
            // ...
        }
    }
    

4. Impersonation Fix

  • Bug Fix: Impersonation no longer deauthenticates on every request:
    // app/Http/Middleware/ImpersonateUser.php
    public function handle(Request $request, Closure $next)
    {
        if ($request->has('impersonate')) {
            $this->auth()->impersonate($request->user(), $request->input('impersonate'));
        }
        return $next($request);
    }
    

5. X.509 Authentication (Updated)

  • Security Fix: Anchor emailAddress regex to RDN boundary:
    // config/security.php
    'firewalls' => [
        'x509' => [
            'pattern' => '^/x509',
            'x509' => [
                'subject' => ['CN=%u'], // Updated to use RDN boundary
            ],
        ],
    ],
    

Gotchas and Tips

1. HEAD Request Bypass Fixes (Critical)

  • Issue: HEAD requests could bypass IsGranted, IsCsrfTokenValid, and IsSignatureValid attributes.
    • Fix: Explicitly define allowed methods in attributes:
      #[IsGranted('ROLE_ADMIN', methods: ['GET', 'POST'])] // Only allow GET/POST
      public function adminAction()
      {
          // ...
      }
      
    • Workaround: Use middleware to block HEAD requests globally:
      // app/Http/Middleware/BlockHeadRequests.php
      public function handle(Request $request, Closure $next)
      {
          if ($request->isMethod('HEAD')) {
              abort(405, 'HEAD method not allowed');
          }
          return $next($request);
      }
      

2. CAS Authentication Requirements

  • Gotcha: CAS now requires trusted_hosts configuration (CVE-2026-45074).
    • Fix: Always define trusted hosts:
      'firewalls' => [
          'cas' => [
              'cas' => [
                  'trusted_hosts' => ['yourdomain.com', 'localhost'], // Mandatory
              ],
          ],
      ],
      

3. OIDC Claim Handling (Security Update)

  • Gotcha: Missing claims in OidcTokenHandler could lead to authentication issues (CVE-2026-45069).
    • Fix: Explicitly define claims in configuration:
      'providers' => [
          'oidc' => [
              'claims' => ['email', 'name', 'preferred_username'], // Required
          ],
      ],
      
    • Debug: Verify claims are present in the user object:
      #[CurrentUser]
      public function debug(UserInterface $user)
      {
          dd($user->getUserIdentifier(), $user->getRoles());
      }
      

4. Impersonation Stability

  • Bug Fix: Impersonation no longer breaks on subsequent requests.
    • Tip: Clear impersonation when done:
      public function stopImpersonating()
      {
          $this->auth()->stopImpersonating();
          return back();
      }
      

5. CSRF Token Validation (Hardened)

  • Gotcha: CSRF tokens now strictly validate against allowed methods.
    • Fix: Ensure forms/AJAX include the correct method:
      <form method="POST" action="/update">
          @csrf
          <!-- CSRF token is automatically included -->
      </form>
      
    • AJAX: Pass the token with the correct method:
      fetch('/update', {
          method: 'POST', // Must match attribute's allowed methods
          headers: {
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
              'Content-Type': 'application/json',
          },
      });
      

6. Extension Points (Updated)

  • Custom Firewall Listeners: Leverage the updated middleware system:
    use Symfony\Component\Security\Http\Middleware\FirewallMiddleware;
    
    // Register in Kernel.php
    protected $middleware = [
        FirewallMiddleware::class,
    ];
    
  • Event Listeners: Use Symfony’s event system for pre/post-auth logic:
    use Symfony\Component\Security\Http\Event\AuthenticatorFailureEvent;
    
    $eventDispatcher->addListener(
        AuthenticatorFailureEvent::class,
        function (AuthenticatorFailureEvent $event) {
            // Custom failure logic
        }
    );
    

7. Testing Authenticated Requests (Updated)

  • New Approach: Use Symfony’s AuthenticationUtils for testing:
    use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
    
    public function testAuthenticatedRoute()
    {
        $authUtils = $this->app->make(AuthenticationUtils::class);
        $authUtils->startAuthentication('main', new Request());
    
        $response = $this->get('/admin');
        $response->assertStatus(200);
    }
    
  • Laravel Testing Helper:
    $response = $this->actingAs(User::find(1))
        ->withHeaders(['X-CSRF-TOKEN' => csrf_token()])
        ->post('/update');
    

8. Performance: Claim Caching

  • Tip: Cache OIDC claims to reduce provider calls:
    'providers' => [
        'oidc' => [
            'claims_cache_ttl' => 60, // Cache claims for 60 seconds
        ],
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle