2

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

Awais Arif
  • 51
  • 6
  • I'm not sure I understand the question. As far as I know sanctum integrates with laravel's authentication mechanism so if you use that in your own package as well it should work just fine – apokryfos Feb 24 '22 at 07:38
  • I added route prefix with middleware of api – Awais Arif Mar 01 '22 at 14:00

2 Answers2

1

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

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

Sajid
  • 26
  • 1
1

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.

  • I agree. I have a custom package and when I added just `auth:sanctum` to web.php the route didn't work. It kept on redirecting to /dashboard. But after I added `web` it started working. – Eugene van der Merwe Oct 01 '22 at 19:00