How to access Sanctum package in custom laravel package

514 Views Asked by At

i want to access laravel sanctum auth which is working fine in project routes I'm making a custom package of api's which needs to use same sanctum authentication with in the custom package routes

2

There are 2 best solutions below

1
Sajid On BEST ANSWER

use auth sanctum middleware for your routes, See below example.

https://laravel.com/docs/9.x/sanctum#protecting-routes

1
Macedo_Montalvão On

I was having the same problem, but I found that the packet routes did not have a default guard and the session was not accessible through the packet.

The solution was to add the 'web' middleware to the routes.

Before:

Route::get('/dashboard', [HomeController::class, 'index'])->middleware(['auth:sanctum'])->name('dashboard');

After:

Route::get('/dashboard', [HomeController::class, 'index'])->middleware(['web', 'auth:sanctum'])->name('dashboard');

For those who don't understand why this happens, the question is simple, the 'web' guard is automatically added to the routes that are in the web.php file, but for some reason this doesn't happen with the routes of packages.

Why is the 'web' guard necessary?

Actually, the 'web' guard is not needed, the point is that it bundles various middlewares including: \Illuminate\Session\Middleware\StartSession, which is what handles the user session, so if you don't want to include the 'web' guard in the routes, you you can create a custom middleware group with everything needed for your routes to work in the app\Http\Kernel.php file and the problem will be solved.