Auth guard [:api] is not defined?

Viewed 15457

when I use auth api gaurd for logout route. I am facing with 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 file



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

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

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 logout the user

3 Answers

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

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,
    ],
],

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',
        ....
    ],
Related