laravel sanctum : custom middleware always return false

Viewed 30

I am using Laravel 9 with two custom Authenticatable models, Admin and Company, them are both extends from User.php, which is using Laravel Sanctum as the tokens generator.

app\Models\User.php

abstract class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $guard_name = 'sanctum';
}

routes/api.php

// admin user tokens
Route::group([
    'as' => 'admin.',
    'namespace' => 'Admin',
    'middleware' => [
        'guest:admin'
    ],
], function() {
    Route::post('tokens','TokensController@store')->name('tokens.store');
});

Route::group([
    'as' => 'admin.',
    'namespace' => 'Admin',
    'middleware' => [
        'auth:admin'
    ],
], function() {
    Route::get('tokens','TokensController@index')->name('tokens.index');
});

// company user tokens
Route::group([
    'as' => 'company.',
    'namespace' => 'Company',
    'middleware' => [
        'guest:company'
    ],
], function() {
    Route::post('tokens','TokensController@store')->name('tokens.store');
});

Route::group([
    'as' => 'company.',
    'namespace' => 'Company',
    'middleware' => [
        'auth:company'
    ],
], function() {
    Route::get('tokens','TokensController@index')->name('tokens.index');
});

configs/auth.php

return [
    'defaults' => [
        'guard' => 'sanctum',
    ],
    'guards' => [
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'company' => [
            'driver' => 'session',
            'provider' => 'companies',
        ],
    ],
    'providers' => [
        'admins' => [
            'driver' => 'eloquent',
            'model' => \App\Models\Admin::class,
        ],
        'companies' => [
            'driver' => 'eloquent',
            'model' => \App\Models\Company::class,
        ],
    ],
];

app/sanctum.php

    'guard' => [
        'admin',
        'company',
    ],

When store a new token, both admin and company can create a token, but none of the middleware works.

It means when I have a correct Authorization header, but I can still create a new token (TokensControlller@store), however I can't access the tokens list (TokensControlller@index)

The auth:admin and auth:company always return false, and guest:admin and guest:company always return true.


The strange thing is, when I using 'middleware' => 'auth' instead of 'middleware' => 'auth:admin', it works but not correct (a company user token can access the GET:/admin/auth/tokens)


How can I debug the auth middleware or how can I fix this?

I googled it a lot but nothing helps, thanks a lot in advance!

0 Answers
Related