我在Laravel 5.2中使用无状态HTTP基本身份验证构建API,根据文档Stateless HTTP Basic Authentication ,我创建了以下中间件
应用程序/ 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中注册它
应用程序/ 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::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: Class App \ Http \ Middleware \ AuthenticateOnceWithBasicAuth不存在
我运行了以下命令,但没有成功
composer dump-autoload
php artisan clear-compiled
php artisan optimize
非常感谢任何帮助。提前谢谢。
答案 0 :(得分:7)
首先看看命名空间:
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);
}