Laravel 7中实现类l5-very-basic-auth的BasicAuth及独立账号验证咨询
Hey there! Let's break down how to solve your Laravel 7 Basic Auth needs, both for a simple l5-very-basic-auth style setup and authenticating against a custom table instead of the default users table.
1. Implementing a Simple Basic Auth (Like l5-very-basic-auth)
The l5-very-basic-auth package provides a no-frills HTTP Basic Auth that doesn't rely on Laravel's default user authentication system. You can replicate this with a custom middleware in just a few steps:
Create a custom middleware
Run this Artisan command to generate a new middleware:php artisan make:middleware VeryBasicAuthAdd the authentication logic
Openapp/Http/Middleware/VeryBasicAuth.phpand replace the content with this:<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class VeryBasicAuth { public function handle(Request $request, Closure $next) { // Pull valid credentials from your config (you can use env vars too) $validUsername = config('auth.very_basic.username'); $validPassword = config('auth.very_basic.password'); // Validate the incoming Basic Auth credentials if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] !== $validUsername || $_SERVER['PHP_AUTH_PW'] !== $validPassword) { header('WWW-Authenticate: Basic realm="Protected Area"'); header('HTTP/1.0 401 Unauthorized'); echo 'Unauthorized access. Please provide valid credentials.'; exit; } return $next($request); } }Add config values
Openconfig/auth.phpand add this section at the bottom:'very_basic' => [ 'username' => env('VERY_BASIC_USERNAME', 'admin'), 'password' => env('VERY_BASIC_PASSWORD', 'secret123'), ],You can also set these values in your
.envfile for better security:VERY_BASIC_USERNAME=your_custom_user VERY_BASIC_PASSWORD=your_secure_passwordRegister the middleware
Inapp/Http/Kernel.php, add this entry to the$routeMiddlewarearray:'very-basic-auth' => \App\Http\Middleware\VeryBasicAuth::class,Use it in your routes
Apply the middleware to your protected route like this:Route::get('/show', 'Controller@show')->name('debugShow')->middleware('very-basic-auth');
2. Authenticating Against a Custom Table with AuthenticateWithBasicAuth
The default auth.basic middleware uses Laravel's default users table, but you can easily adapt it to work with a custom table (e.g., admins, employees, etc.). Here are two approaches:
Option 1: Use the native auth.basic middleware with custom guard/field
This is the quickest way if you've already set up a custom authentication guard for your table:
First, configure your custom guard and provider in config/auth.php:
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'custom' => [ // Name this whatever makes sense for your table 'driver' => 'session', 'provider' => 'custom_users', ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], 'custom_users' => [ 'driver' => 'eloquent', 'model' => App\Models\CustomUser::class, // Your custom model ], ],
Then, use the auth.basic middleware with your guard and optional field (default is email):
// Format: auth.basic:guard_name,authentication_field Route::get('/show', 'Controller@show')->name('debugShow')->middleware('auth.basic:custom,username');
Replace custom with your guard name and username with the field you want to use for authentication (e.g., email, user_id).
Option 2: Create a custom middleware extending AuthenticateWithBasicAuth
If you need more control, create a dedicated middleware that extends Laravel's built-in AuthenticateWithBasicAuth:
Generate the middleware
php artisan make:middleware CustomBasicAuthUpdate the middleware code
Openapp/Http/Middleware/CustomBasicAuth.phpand use this code:<?php namespace App\Http\Middleware; use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth; use Illuminate\Contracts\Auth\Factory as AuthFactory; class CustomBasicAuth extends AuthenticateWithBasicAuth { public function __construct(AuthFactory $auth) { parent::__construct($auth); } protected function authenticate($request, array $guards) { // Use your custom guard and authentication field here $this->auth->guard('custom')->basic('username'); } }Register the middleware
Add this toapp/Http/Kernel.php's$routeMiddlewarearray:'auth.custom.basic' => \App\Http\Middleware\CustomBasicAuth::class,Apply it to your route
Route::get('/show', 'Controller@show')->name('debugShow')->middleware('auth.custom.basic');
Either approach will let you authenticate against your custom table instead of the default users table.
内容的提问来源于stack exchange,提问作者Iw Yu

