'auth'中间件在流明投掷错误

时间:2015-07-22 13:39:55

标签: laravel-5 laravel-routing lumen laravel-middleware

我是第一次测试流明。试用auth中间件会引发错误。我想知道这样的中间件是否带有内腔,还是我们需要实现自己的? 这是我的路线文件

$app->group(['middleware' => 'auth'], function ($app) {

    $app->get('/', ['as' => 'api', 'uses' => 'ApiController@index']);
});

这是尝试访问路径时的错误

ErrorException in Manager.php line 137:
call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Auth\Guard' does not have a method 'handle'

2 个答案:

答案 0 :(得分:4)

如您所见,Lumen容器中的auth绑定到Illuminate\Support\Manager\AuthManager。所以,是的,你必须创建自己的中间件。这是您案例的一个例子。

app/Http/Middleware

中制作您自己的中间件
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                // Lumen has no Redirector::guest(), this line is put the intended URL to a session like Redirector::guest() does
                app('session')->put('url.intended', app('url')->full());
                // Set your login URL here
                return redirect()->to('auth/login', 302);
            }
        }

        return $next($request);
    }
}

在此之后,将中间件绑定到容器中。您可以在bootstrap/app.php中执行此操作。在return之前添加这两行。

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__.'/../app/Http/routes.php';
});

$app->bind('App\Http\Middleware\Authenticate', 'App\Http\Middleware\Authenticate');
$app->alias('App\Http\Middleware\Authenticate', 'middleware.auth');

现在,不要在中间件中使用auth,而是使用middleware.auth

$app->group(['middleware' => 'middleware.auth'], function ($app) {
    $app->get('/', ['as' => 'api', 'uses' => 'ApiController@index']);
});

答案 1 :(得分:2)

实际上,您需要做的就是在bootstrap/app.php

中取消注释这些行
$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);