vinkla/shield

This package is abandoned and no longer maintained. The author suggests using the https://github.com/vinkla/laravel-shield#readme package instead.

A HTTP basic auth middleware for Laravel

9.0.0 2023-02-14 10:29 UTC

README

This package used to be an HTTP basic auth middleware for Laravel. However, it is now deprecated as I no longer use it personally. Laravel already has built-in basic auth support for their web guard.

If you need simpler basic auth for your API, instead of depending on a third-party library, you can add it yourself. Please follow the guide below.

To begin, update your .env file with the following details:

BASIC_AUTH_USER=your-username
BASIC_AUTH_PASSWORD=your-password

Modify your config/auth.php file as follows:

'basic' => [
    'user' => env('BASIC_AUTH_USER'),
    'password' => env('BASIC_AUTH_PASSWORD'),
],

Finally, create a middleware that resembles the code below:

<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class BasicAuthMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = config('auth.basic.user');
        $password = config('auth.basic.password');

        if (
            $request->getUser() !== $user ||
            $request->getPassword() !== $password
        ) {
            throw new UnauthorizedHttpException('Basic');
        }

        return $next($request);
    }
}

That's it! You can now use the middleware in your routes.

use App\Http\Middleware\BasicAuthMiddleware;
use App\Models\User;

Route::get('api/users', function () {
    return User::all();
})->middleware(BasicAuthMiddleware::class);