Laravel 11配置固定凭证的Basic Auth保护未完成应用
Laravel 11 配置固定凭证的HTTP Basic认证
要实现所有人使用固定凭证(如foo/bar)的Basic Auth,无需依赖Laravel默认的用户表验证,直接自定义中间件即可,步骤如下:
创建自定义Basic Auth中间件
执行Artisan命令生成中间件文件:php artisan make:middleware BasicAuthFixedCredentials编写固定凭证验证逻辑
打开生成的app/Http/Middleware/BasicAuthFixedCredentials.php,替换handle方法内容:<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class BasicAuthFixedCredentials { public function handle(Request $request, Closure $next): Response { // 提取Basic Auth凭证 $credentials = $request->getUser(); $password = $request->getPassword(); // 验证固定凭证 if ($credentials !== 'foo' || $password !== 'bar') { return response('Unauthorized', Response::HTTP_UNAUTHORIZED, [ 'WWW-Authenticate' => 'Basic realm="Your App Name"', ]); } return $next($request); } }注册中间件(Laravel 11)
在bootstrap/app.php中,将自定义中间件添加到路由中间件别名,方便路由调用:return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', api: __DIR__.'/../routes/api.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { // 添加自定义中间件别名 $middleware->alias([ 'auth.basic.fixed' => \App\Http\Middleware\BasicAuthFixedCredentials::class, ]); }) ->create();替换全局/路由组的中间件
把原来全局应用的auth.basic换成自定义的auth.basic.fixed:- 如果是全局中间件,在
bootstrap/app.php的withMiddleware里添加到web或api组; - 如果是路由组应用,直接在路由文件里修改:
Route::middleware('auth.basic.fixed')->group(function () { // 所有需要验证的路由 }); // 排除webhook路由 Route::post('/payments/verify', [PaymentsController::class, 'verify']) ->name('payments.verify') ->withoutMiddleware('auth.basic.fixed');
- 如果是全局中间件,在
这样配置后,所有受中间件保护的路由都会要求输入固定的foo/bar凭证,支付服务商的webhook路由则不受影响。
内容的提问来源于stack exchange,提问作者Matt Komarnicki
相关产品推荐
相关产品推荐

