API JWT guard and web session guard in Laravel

2.9k Views Asked by At

I am trying to make Laravel using multiple guards - depending on the authentication type.

When I am authenticating via API, I would like to use jwt guard. When I am authenticating through web, I want to use session guard.

My config\auth.php looks like this:

'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
            //'hash' => false,
        ],
    ],

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
]

My routes/web.php looks like this:

Route::get('/', 'HomeController@index')->name('home');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');

My routes/api.php looks like this:

Route::post('login', 'AuthController@login');
Route::get('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
Route::get('me', 'AuthController@me');

What I am getting is that API authentication works fine, while the web doesn't. I have debugged and it seems like it is always checking the jwt guard.

Can someone help me, how can I set the guard on a route if that is possible or on Auth::routes() call?

1

There are 1 best solutions below

0
On

I have solved it by switching default to web routes.

Then I updated the code for app/Http/Controllers/AuthController.php to use the specific api auth wherever I was using the auth method:

auth('api')->attempt($validator->validated()) and 'expires_in' => auth('api')->factory()->getTTL() * 60