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

Httpauth Laravel Package

intervention/httpauth

Intervention Httpauth is a lightweight Laravel/PHP package for adding HTTP authentication to your app. Protect routes with Basic or Digest auth, integrate easily with middleware, and configure credentials and realms for quick, standards-based access control.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require intervention/httpauth
    

    Add to composer.json if not auto-loaded:

    "autoload": {
        "psr-4": {
            "Intervention\\HttpAuth\\": "vendor/intervention/httpauth/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Basic Auth Middleware Create a middleware (app/Http/Middleware/AuthBasic.php):

    use Intervention\HttpAuth\BasicAuth;
    use Closure;
    
    class AuthBasic extends Middleware
    {
        public function handle($request, Closure $next)
        {
            $auth = new BasicAuth();
            $auth->setRealm('Admin Area');
    
            if (!$auth->check($request->user(), $request->password())) {
                return response('Unauthorized', 401, [
                    'WWW-Authenticate' => $auth->getHeader()
                ]);
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $routeMiddleware = [
        'auth.basic' => \App\Http\Middleware\AuthBasic::class,
    ];
    

    Apply to routes:

    Route::get('/admin', function () {
        return 'Admin Dashboard';
    })->middleware('auth.basic');
    
  3. First Use Case: Digest Auth Replace BasicAuth with DigestAuth in the middleware and ensure the client sends credentials in the Authorization header.


Implementation Patterns

Middleware Integration

  • Reusable Auth Logic: Encapsulate auth checks in middleware for route-level protection.
  • Dynamic Realms: Use middleware to set realms dynamically:
    $auth->setRealm('User: ' . $user->name);
    
  • Multi-Auth Routes: Combine with Laravel’s built-in auth:
    Route::group(['middleware' => ['auth.basic', 'auth:sanctum']], function () {
        // Requires both Basic Auth and Sanctum token
    });
    

Request Handling

  • Manual Validation: Validate headers outside middleware:
    $auth = new BasicAuth();
    if ($auth->check($request->header('PHP_AUTH_USER'), $request->header('PHP_AUTH_PW'))) {
        // Proceed
    }
    
  • Header Manipulation: Modify responses to include auth headers:
    return response()->json(['data'], 200, [
        'WWW-Authenticate' => $auth->getHeader()
    ]);
    

Testing

  • Mock Auth Headers: Simulate auth in tests:
    $response = $this->withHeaders([
        'PHP_AUTH_USER' => 'user',
        'PHP_AUTH_PW' => 'pass'
    ])->get('/admin');
    
  • Assert Auth Challenges: Verify 401 responses with auth headers:
    $response->assertStatus(401)
             ->assertHeader('WWW-Authenticate', 'Basic realm="Admin Area"');
    

Advanced Patterns

  • Custom Auth Schemes: Extend Intervention\HttpAuth\Auth for custom logic:
    class ApiKeyAuth extends Auth
    {
        public function check($key) {
            return Hash::check($key, config('app.api_key'));
        }
    }
    
  • Rate Limiting + Auth: Combine with Laravel’s throttling:
    Route::middleware(['throttle:60,1', 'auth.basic'])->group(function () {
        // Rate-limited auth-protected routes
    });
    

Gotchas and Tips

Pitfalls

  1. Header Case Sensitivity:

    • Laravel’s $request->header() is case-insensitive, but PHP_AUTH_USER/PHP_AUTH_PW are case-sensitive in the Authorization header.
    • Fix: Use $request->header('authorization') and parse manually if needed:
      $authHeader = $request->header('authorization');
      if (preg_match('/Basic (.*)/', $authHeader, $matches)) {
          list($user, $pass) = base64_decode($matches[1]);
      }
      
  2. Digest Auth Complexity:

    • Digest auth requires nonce, opaque, and algorithm handling. The package simplifies this, but ensure:
      • Nonces are unique and time-bound (store in session/database).
      • Clients support the algorithm (e.g., MD5 is widely supported but weak).
    • Tip: Use DigestAuth::setNonce() with a timestamp:
      $auth->setNonce(time() . '-' . Str::random(10));
      
  3. Middleware Caching:

    • Middleware runs on every request, even for static assets. Exclude assets from auth:
      Route::middleware('auth.basic')->group(function () {
          Route::get('/admin/{any}', function () { /* ... */ })->where('any', '.*');
      });
      
  4. Password Hashing:

    • Never store plaintext passwords. Use Laravel’s Hash::check():
      if (Hash::check($request->password, $user->password)) {
          // Valid
      }
      

Debugging Tips

  • Log Headers: Dump auth headers for debugging:
    \Log::debug('Auth Headers', [
        'PHP_AUTH_USER' => $request->header('PHP_AUTH_USER'),
        'Authorization' => $request->header('authorization'),
    ]);
    
  • Test with curl:
    curl -u user:pass http://localhost/admin
    
    For Digest Auth:
    curl --digest -u user:pass http://localhost/admin
    

Extension Points

  1. Custom Validation:
    • Override Auth::check() to add logic (e.g., IP whitelisting):
      public function check($user, $pass) {
           return parent::check($user, $pass) && $this->isIpAllowed($request->ip());
       }
      
  2. Event-Based Auth:
    • Dispatch events on auth success/failure:
      if ($auth->check($user, $pass)) {
          event(new Authenticated($user));
      } else {
          event(new AuthenticationFailed($user));
      }
      
  3. Package Integration:
    • Use with Laravel Fortify/Passport for hybrid auth:
      Route::middleware(['auth.basic', 'auth:sanctum'])->get('/secure');
      

Configuration Quirks

  • No Built-in Config: The package is lightweight; configure realms/nonces in middleware or controllers.
  • Thread Safety: Nonces must be unique per session. Use Laravel’s session() helper:
    $auth->setNonce(session()->get('digest_nonce', Str::random(32)));
    
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle