gpt4 book ai didi

laravel - ReflectionException-中间件类不存在Laravel 5.2

转载 作者:行者123 更新时间:2023-12-04 14:25:05 24 4
gpt4 key购买 nike

根据文档Stateless HTTP Basic Authentication ,我在Laravel 5.2中使用无状态HTTP基本身份验证构建API,我创建了以下中间件

app/Http/中间件/AuthenticateOnceWithBasicAuth.php

<?php

namespace Illuminate\Auth\Middleware;

use Auth;
use Closure;

class AuthenticateOnceWithBasicAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/

public function handle($request, Closure $next)
{
return Auth::onceBasic() ?: $next($request);

}

}

然后在Kernel.php中注册

app/Http/kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'auth.basic.once' => \App\Http\Middleware\AuthenticateOnceWithBasicAuth::class,
];

我在如下 route 使用它
Route::group(['prefix' => 'admin', 'middleware' => 'auth.basic.once'], function () {

Route::get('service/create', function () {
return response()->json(['name' => 'Abigail', 'state' => 'CA'], 200);
});

});

但这给了我

Container.php第734行的ReflectionException:
类App\Http\Middleware\AuthenticateOnceWithBasicAuth不存在

enter image description here

我已经执行以下命令,但没有成功
composer dump-autoload
php artisan clear-compiled
php artisan optimize

任何帮助将非常感激。提前致谢。

最佳答案

首先,请看一下命名空间:

namespace Illuminate\Auth\Middleware;

您应该将其重命名为:
namespace App\Http\Middleware;

在中间件中,您需要执行以下操作:
public function handle($request, Closure $next) {
if (!Auth::onceBasic()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}

return $next($request);
}

关于laravel - ReflectionException-中间件类不存在Laravel 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37568881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com