Laravel session-based authentication: api middleware not working

I tried using Auth Scaffolding from Laravel 5.3, including api routes. I wanted to use the session driver for the api guard, but apparently this has no effect. After entering the application with a valid user (so I get from /loginto /home), I tried to enter the path /api/user, but it always redirects me to /home. The tool RedirectIfAuthenticatedredirects the user.

Here's what I tried and a quick review of the test application:

// In "app\Http\Middleware\RedirectIfAuthenticated.php"
if (Auth::guard($guard)->check()) {
    return redirect('/home');
}

$guardis null, and if is when viewed on /api/user.

// In "config\auth.php"
'api' => [
    'driver' => 'session', // changed from token to session
    'provider' => 'users',
],

I changed the api protection driver to session.

// In "app\Http\Kernel.php"
'api' => [
    'throttle:60,1',
    'bindings',
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
],

I added middlewares to support cookies in api middleware

// In "routes\api.php"
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

, Laravel.

// In "app\Providers\RouteServiceProvider.php"
Route::group([
    'middleware' => 'api',
    'namespace' => $this->namespace,
    'prefix' => 'api',
], function ($router) {
    require base_path('routes/api.php');
});

api , api.php.

API .. , Laravel 5.2, , web auth . Laravel 5.3 auth .

. :

// In "routes\web.php"
Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth']);

, , web api auth.php.

Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth:api']);
+4
1

/home API, . api Kernel.php "" , .

0

Source: https://habr.com/ru/post/1660852/


All Articles