Laravel 5.2: session和token保护在相同的路由上


Laravel 5.2: session and token guard on the same routes

我们有会话保护,这就足够了。

现在我们需要在相同的路由上通过令牌(在报头或GET参数中)和会话添加授权。

通过令牌的授权必须是无状态的。

乌利希期刊指南:首先,我们考虑创建重复路由。一个用于会话,一个用于令牌

// api token auth
// url: /api/test
Route::group(['middleware' => ['web', 'auth:api'], 'prefix' => 'api', 'as' => 'api.'], function () {
    Route::resource('test', 'TestController');
    // 50+ routes
});
// session auth
// url: /test
Route::group(['middleware' => ['web', 'auth']], function () {
    Route::resource('test', 'TestController');
    // 50+ routes
});

但这不是我们想要的,因为url是不同的。

也许有人知道如何解决这个问题?

创建新的中间件AuthenticateWithToken:

class AuthenticateWithToken
{
    /**
     * Handle an incoming request.
     *
     * @param  'Illuminate'Http'Request  $request
     * @param  'Closure  $next
     * @param  string|null  $guard
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (($user = Auth::guard('api')->user())) {
            Auth::setUser($user);
        }
        return $next($request);
    }
}

在Http/Kernel.php声明:

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    // ...
    'auth.api' => 'App'Http'Middleware'AuthenticateWithToken::class,
    // ...
];

并将其添加到routes.php中默认的'auth'中间件之前:

Route::group(['middleware' => ['web', 'auth.api', 'auth']], function () {
    Route::resource('test', 'TestController');
    // 50+ routes
});