Alexander Anikeev Alexander Anikeev - 2 months ago 15
PHP Question

Laravel 5.2: session and token guard on the same routes

We had session guard and that was enough.

Now we need to add authorization via token (in headers or GET params) and via session on the same routes.

Authorization via token must be stateless.

UPD:
First, we think about create dubplicate routes.
One for session and one for token

// 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
});


but it's not what we want, because urls are different.

Maybe somebody knows how to solve this issue?

Answer

Create new middleware 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);
    }
}

Declare it in 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,
    // ...
];

And add it before default 'auth' middleware in routes.php:

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