laravel-modules: Middleware auth:sanctum not working in Module route
I installed ‘Laravel/sanctum’ through composer and published the vendor and migrated migrations and used Laravel\Sanctum\HasApiTokens on Entitites/User. There is an api route file on user module and ‘auth:sanctum’ middleware is used on ‘/api/me’ route. It should send Unauthenticated JSON response when there is no token, but when i hit this api without token, its showing login page even if i had used Accept: application/json as header.
Also im not able to hit this api even if i have sent the current token.
This is my api route file:
Route::post('/login', 'AuthController@login')->name('api.login'); Route::group(['middleware' => ['auth:sanctum']], function () { Route::get('/me', 'AuthController@getLoggedUser')->name('api.me'); });
This is the response i’m getting when I hit on postman.
Is there something I need to do to be able to use the middleware in the module?
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 1
- Comments: 19
Faced with the same problem. After some investigation it seems the problem happens there: https://github.com/laravel/sanctum/commit/f5695aecc547138c76bc66aaede73ba549dabdc5
During the refactoring they forgot to include default guard definition.
Just add this at the end of config/sanctum.php for api guard:
'guard' => 'api'
Am new to laravel and I had the same problem, but I solved it by changing the gurds in the file config/auth.php to `
And changed the routes/api.php groups to `
Route::group([‘middleware’ => ‘auth:api’], function () { Route::get(‘articles’, [MyController::class, ‘index’]); });
`
GOOD LUCK
i faced the same Issue but i solved it by Add to headers Accept with value application/json
that’s the best solution i found maybe others have another solution.
I think your AuthController contains a __construct() method, that was the case for me, I removed it and the middleware got applied on the request, I think that the reason is the __construct() method clears the middlewares array, so make sure you don’t have one on your controller. Hope it works for you!
then you must have include to $middleware list line below on Kernel.php
\App\Http\Middleware\XAuthorizationHeader::class,
In my case cpanel apache denied Authorization header even i configured on htaccess file. So i created XauthorizationHeader middleware then my problem solved…