Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel session based auth:api middleware not working

I tried using the Auth Scaffolding of Laravel 5.3 including the api routes. I wanted to use the session driver for the api guard, but apparently this has no impact whatsoever. After I log into the application with a valid user (so I get from /login to /home) I tried entering the path /api/user, but it always redirects me to /home. The RedirectIfAuthenticated middleware redirects the user.

Here is what I tried and a quick overview of the test application:

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

$guard is null, and the if is true when browsing to /api/user.

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

I changed the driver of the api guard to session.

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

I added the middlewares to support cookies in the api middleware

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

This is an example that comes with a new Laravel installation.

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

The api middleware is applied to all the routes defined in the api.php file.

I want to be able to query my API after a user has logged in without using tokens, etc. The app I wrote with Laravel 5.2 had basically the same route but only the web middleware group and auth middleware applied to it. In Laravel 5.3, adding the auth middleware leads to the described problem.

edit: With my configuration I tried the following:

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

This works perfectly fine, but this doesn't, although the web and the api guard are exactly the same inside the auth.php.

Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth:api']);
like image 886
Johannes Avatar asked Nov 15 '16 21:11

Johannes


1 Answers

I had the same issue of getting redirected to the /home while accessing my API routes even if I was already logged in. Try changing the order of your api middlewares in App\Http\Kernel.php and place bindings in last position so your custom middlewares are executed first.

like image 71
Andrea Mauro Avatar answered Sep 23 '22 19:09

Andrea Mauro