HAMZA HUMMAM
HAMZA HUMMAM

Reputation: 372

Auth guard [:api] is not defined?

When I use auth:api guard for the logout route, I'm facing the following exception:

Auth guard [:api] is not defined

I have already implemented registration/login APIs, but I am facing this error with logout API, which I had protected using auth::api.

config/auth.php:

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

routes/api.php:

Route::group(['prefix' => 'auth'], function () {
    Route::post('login','AuthController@login');
    Route::post('signup','AuthController@signup');

    Route::group(['middleware' => 'auth::api'], function () {
        Route::get('logout','AuthController@logout');
        Route::get('user','AuthController@user');
    });
});

I should be able to log out the user.

Upvotes: 18

Views: 36833

Answers (3)

pableiros
pableiros

Reputation: 16032

If you are using Laravel 9+ and Passport, you need to implemented this inside the guard array on config/auth.php file:

'guards' => [
    ...

    // you need to implement this
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        'hash' => true,
    ],
],

Upvotes: 10

mahi samia
mahi samia

Reputation: 21

I had the same issue, it seems that i forgot to change Authentication Defaults so in config/auth.php change this

    'defaults' => [
        'guard' => 'web',
        ....
    ],

into this

    'defaults' => [
        'guard' => 'api',
        ....
    ],

Upvotes: 1

Remul
Remul

Reputation: 8252

You have an extra colon in your code, that's why it is trying to find the guard :api.

According to the docs:

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

Route::put('post/{id}', function ($id) {
    //
})->middleware('role:editor');

So in your case it would be:

Route::group(['prefix' => 'auth'], function () {
    Route::post('login','AuthController@login');
    Route::post('signup','AuthController@signup');

    Route::group(['middleware' => 'auth:api'], function () {
        Route::get('logout','AuthController@logout');
        Route::get('user','AuthController@user');
    });
});

Upvotes: 2

Related Questions