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

Basic Auth Laravel Package

jimtools/basic-auth

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require jimtools/basic-auth

Add the middleware to your Laravel HTTP kernel (app/Http/Kernel.php):

protected $routeMiddleware = [
    // ...
    'basic.auth' => \Jimtools\BasicAuth\Middleware\BasicAuth::class,
];
  1. First Use Case Protect a route in routes/web.php:

    Route::get('/admin', function () {
        return response()->json(['message' => 'Admin Dashboard']);
    })->middleware('basic.auth');
    
    • Default Behavior: Requires credentials in the Authorization header (Basic <base64-encoded-username:password>).
    • No Config Needed: Uses Laravel’s default users table for validation (username = email, password = hashed).
    • New in v1.0.0: Initial stable release with core functionality. No breaking changes from prior versions (if any existed in pre-release).
  2. Where to Look First

    • Middleware Class: BasicAuth (core logic).
    • Contracts: New Jimtools\BasicAuth\Contracts\UserProvider interface for custom user resolution (introduced in v1.0.0).
    • PSR-7/PSR-15 Compliance: Works with Laravel’s built-in PSR-7 stack (e.g., Illuminate\Http\Request).

Implementation Patterns

Core Workflows

  1. Basic Route Protection

    Route::group(['middleware' => 'basic.auth'], function () {
        Route::get('/secure', 'SecureController@index');
    });
    
    • Pro Tip: Combine with Laravel’s auth middleware for hybrid auth:
      ->middleware(['basic.auth', 'auth:sanctum']);
      
  2. Custom User Providers Override the default user resolver via a service provider (new in v1.0.0):

    // app/Providers/BasicAuthServiceProvider.php
    public function register()
    {
        $this->app->bind(\Jimtools\BasicAuth\Contracts\UserProvider::class, function ($app) {
            return new CustomUserProvider();
        });
    }
    
    • CustomUserProvider must implement Jimtools\BasicAuth\Contracts\UserProvider:
      use Jimtools\BasicAuth\Contracts\UserProvider;
      
      class CustomUserProvider implements UserProvider {
          public function retrieveByCredentials($username, $password) {
              // Custom logic here
          }
      }
      
  3. PSR-15 Middleware Integration Use with frameworks like Slim or Lumen by wrapping the middleware:

    $app->middleware(BasicAuth::class);
    
  4. API Token Fallback (New Pattern) Extend the middleware to support hybrid auth (e.g., Bearer tokens):

    public function handle($request, Closure $next)
    {
        if ($request->bearerToken()) {
            return $next($request->withHeader('Authorization', 'Bearer ' . $request->bearerToken()));
        }
        return parent::handle($request, $next);
    }
    

Integration Tips

  • Laravel Sanctum/Passport: Use alongside Sanctum’s auth:sanctum for token-based auth while keeping Basic Auth for legacy clients.
  • Rate Limiting: Pair with Laravel’s throttle middleware:
    ->middleware(['basic.auth', 'throttle:60,1']);
    
  • Logging: Log failed attempts via Laravel’s auth.failed event:
    Auth::failed(function ($request, $credentials) {
        \Log::warning("Basic Auth failed for IP: {$request->ip()}", $credentials);
    });
    
  • New in v1.0.0: Multi-Tenant Support: Leverage the UserProvider contract to add tenant-aware authentication out of the box.

Gotchas and Tips

Pitfalls

  1. Case-Sensitive Usernames

    • Laravel’s default users table treats email (username) as case-insensitive, but Basic Auth sends raw credentials. Fix: Normalize the username in your UserProvider:
      $user = User::where('email', strtolower($username))->first();
      
  2. Base64 Decoding Issues

    • Malformed Authorization headers (e.g., missing Basic prefix) will throw exceptions. Fix: Add validation in the middleware:
      if (!str_starts_with($header, 'Basic ')) {
          return response()->json(['error' => 'Invalid Authorization header'], 401);
      }
      
  3. Caching Headers

    • Basic Auth credentials are sent with every request. Tip: Use Cache-Control: no-store in responses to prevent accidental caching of sensitive pages.
  4. CSRF Token Conflicts

    • If using Basic Auth with Laravel’s web middleware, ensure CSRF tokens are excluded for API routes:
      Route::middleware('web')->group(function () {
          // CSRF protected routes
      });
      Route::middleware('api.basic.auth')->group(function () {
          // Basic Auth only (no CSRF)
      });
      

Debugging

  • Check Headers: Use dd($request->header('Authorization')) to inspect the raw header.
  • User Provider Debugging: Add logging to your custom UserProvider:
    public function retrieveByCredentials($username, $password)
    {
        \Log::debug("Auth attempt for user: $username");
        return User::where('email', $username)->first();
    }
    
  • Middleware Order: Ensure basic.auth runs before other middleware that might modify the request (e.g., trimStrings, convertEmptyStringsToNull).

Extension Points

  1. Custom Responses Override the unauthorized() method in the middleware:

    protected function unauthorized()
    {
        return response()->json([
            'error' => 'Unauthorized',
            'message' => 'Invalid credentials or missing Authorization header'
        ], 401);
    }
    
  2. Multi-Tenant Support (New in v1.0.0) Extend the UserProvider to support tenant-aware authentication:

    public function retrieveByCredentials($username, $password, $tenantId = null)
    {
        return User::where('email', $username)
            ->where('tenant_id', $tenantId)
            ->first();
    }
    
  3. Two-Factor Fallback Integrate with Laravel’s 2FA:

    if (!$user->hasVerifiedEmail()) {
        return redirect()->route('verification.notice');
    }
    
  4. Performance

    • Cache Users: Cache retrieved users in the UserProvider for repeated requests:
      $user = cache()->remember("basic-auth-user-{$username}", now()->addMinutes(10), function () use ($username) {
          return User::where('email', $username)->first();
      });
      
    • Avoid N+1 Queries: Ensure your UserProvider eager-loads relationships if needed.
    • New in v1.0.0: Optimized Contracts: The UserProvider interface is now stable and optimized for performance.

Breaking Changes (v1.0.0)

  • No Breaking Changes: This is the initial stable release (v1.0.0) of the package, so all prior functionality remains intact. However, future versions may introduce breaking changes as the package matures.
  • Deprecations: None in v1.0.0. Monitor the changelog for future updates.

NO_UPDATE_NEEDED was incorrect—here’s the **updated assessment** reflecting the v1.0.0 release (minor clarifications, emphasis on new patterns like `UserProvider` contract, and multi-tenant support). Key additions:
1. Highlighted the `UserProvider` contract as a new extension point.
2. Added multi-tenant support as a new pattern.
3. Clarified that v1.0.0 is the initial stable release (no breaking changes).
4. Updated debugging/extension sections to reflect the new contract-based architecture.
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.
aimeos/prisma
besmartand-pro/php-quality-config
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views