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

Slim Basic Auth Laravel Package

tuupola/slim-basic-auth

Abandoned PSR-7/PSR-15 middleware providing HTTP Basic Authentication. Originally for Slim but works with any PSR-compatible framework (tested with Slim and Zend Expressive). Configure allowed username/password pairs and protect routes via middleware.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tuupola/slim-basic-auth
    
  2. Basic Usage (Laravel with PSR-7 middleware):

    use Tuupola\Middleware\HttpBasicAuthentication;
    
    $middleware = new HttpBasicAuthentication([
        'users' => [
            'admin' => 'securepassword',
        ],
    ]);
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        // ...
        \App\Http\Middleware\BasicAuth::class,
    ];
    

    Create a Laravel middleware wrapper:

    namespace App\Http\Middleware;
    
    use Closure;
    use Tuupola\Middleware\HttpBasicAuthentication;
    
    class BasicAuth
    {
        public function __construct()
        {
            $this->middleware = new HttpBasicAuthentication([
                'users' => [
                    'admin' => 'securepassword',
                ],
            ]);
        }
    
        public function handle($request, Closure $next)
        {
            return $this->middleware->process($request, new \Slim\Psr7\Response());
        }
    }
    
  3. First Use Case: Protect an API route by adding the middleware to a route group:

    Route::middleware(['basic.auth'])->group(function () {
        Route::get('/api/protected', 'ApiController@protectedMethod');
    });
    

Implementation Patterns

1. Route-Level Protection

  • Pattern: Apply middleware to specific routes or route groups.
    Route::middleware(['basic.auth'])->group(function () {
        Route::get('/admin', 'AdminController@dashboard');
        Route::post('/admin/settings', 'AdminController@updateSettings');
    });
    

2. Dynamic User Validation

  • Pattern: Use a custom authenticator for database-backed auth.
    $middleware = new HttpBasicAuthentication([
        'authenticator' => function ($credentials) {
            return \App\Models\User::where('username', $credentials['user'])
                ->where('password', $credentials['password'])
                ->exists();
        },
    ]);
    

3. Environment-Based Credentials

  • Pattern: Load credentials from .env for security.
    $middleware = new HttpBasicAuthentication([
        'users' => [
            'admin' => env('ADMIN_PASSWORD'),
        ],
    ]);
    

4. Path/Ignore Rules

  • Pattern: Protect specific paths while ignoring others.
    $middleware = new HttpBasicAuthentication([
        'path' => ['/api', '/admin'],
        'ignore' => ['/api/token', '/admin/ping'],
        'users' => ['admin' => 'password'],
    ]);
    

5. Request/Response Hooks

  • Pattern: Modify requests/responses post-authentication.
    $middleware = new HttpBasicAuthentication([
        'before' => function ($request, $args) {
            return $request->withAttribute('authenticated_user', $args['user']);
        },
        'after' => function ($response, $args) {
            return $response->withHeader('X-Auth-User', $args['user']);
        },
        'users' => ['admin' => 'password'],
    ]);
    

6. Custom Error Responses

  • Pattern: Return JSON errors for API consistency.
    $middleware = new HttpBasicAuthentication([
        'error' => function ($response, $args) {
            $body = json_encode(['error' => $args['message']]);
            return $response->withBody(new \Slim\Psr7\Stream($body));
        },
        'users' => ['admin' => 'password'],
    ]);
    

7. HTTPS Enforcement

  • Pattern: Restrict to HTTPS (or whitelist domains).
    $middleware = new HttpBasicAuthentication([
        'secure' => true,
        'relaxed' => ['localhost', 'dev.example.com'], // Allow HTTP for these
        'users' => ['admin' => 'password'],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Double Slash Bypass:

    • Requests like //api may bypass /api protection due to PSR-7 path normalization.
    • Fix: Ensure path rules account for edge cases (e.g., /api/*).
  2. Plaintext Passwords:

    • Hardcoding passwords in code is insecure.
    • Fix: Use .env or hashed passwords (e.g., password_hash()).
  3. HTTPS Misconfiguration:

    • Forgetting secure: true exposes credentials over HTTP.
    • Fix: Always enforce HTTPS in production.
  4. Middleware Order:

    • Place HttpBasicAuthentication before route handlers to block unauthorized access early.
  5. Laravel PSR-7 Integration:

    • Laravel’s native middleware uses Illuminate\Http\Request, not PSR-7.
    • Fix: Use a wrapper (as shown in Getting Started) or convert requests manually.
  6. Custom Authenticator Quirks:

    • The authenticator callback must return bool. Non-boolean values may cause silent failures.
    • Fix: Explicitly cast returns:
      'authenticator' => function ($credentials) {
          return (bool) \App\Models\User::validate($credentials);
      }
      

Debugging Tips

  1. Check Headers:

    • Verify Authorization: Basic ... headers are sent. Use browser dev tools or curl -v.
  2. Log Authentication Attempts:

    • Add logging in the error callback:
      'error' => function ($response, $args) {
          \Log::warning("Auth failed for {$args['user']}: {$args['message']}");
          return $response->withStatus(401);
      }
      
  3. Test Path Matching:

    • Use php artisan route:list to confirm protected routes. Test with:
      curl -u admin:password http://localhost/api/protected
      
  4. Validate Hashes:

    • If using hashed passwords, ensure they match the format (e.g., $2y$... for bcrypt).

Extension Points

  1. Database Auth:

    • Extend PdoAuthenticator for custom queries:
      use Tuupola\Middleware\HttpBasicAuthentication\PdoAuthenticator;
      
      $authenticator = new PdoAuthenticator([
          'pdo' => \DB::connection()->getPdo(),
          'query' => 'SELECT 1 FROM users WHERE username = :user AND password = :password',
      ]);
      
  2. Rate Limiting:

    • Combine with Laravel’s throttle middleware to limit failed attempts:
      Route::middleware(['throttle:60,1', 'basic.auth'])->group(...);
      
  3. Multi-Factor Auth (MFA):

    • Extend the before hook to trigger MFA:
      'before' => function ($request, $args) {
          if (!$request->hasAttribute('mfa_verified')) {
              abort(403, 'MFA required');
          }
          return $request;
      }
      
  4. Dynamic User Lists:

    • Load users from a service (e.g., cache or API):
      $middleware = new HttpBasicAuthentication([
          'users' => \App\Services\AuthService::getUsers(),
      ]);
      

Laravel-Specific Quirks

  • PSR-7 Conversion: Laravel’s Request must be converted to PSR-7 for compatibility. Use a package like fruitcake/laravel-psr7 or write a helper:

    use Psr\Http\Message\ServerRequestInterface;
    use Fruitcake\Psr7\Laravel\ConvertRequest;
    
    $psr7Request = ConvertRequest::fromLaravel($request);
    
  • Middleware Binding: Bind the middleware to routes dynamically:

    Route::get('/admin', function () {
        return 'Protected!';
    })->middleware(BasicAuth::class);
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky