W
W
WotanWeb2021-01-13 17:38:45
Laravel
WotanWeb, 2021-01-13 17:38:45

How to use Auth::user() in Laravel middleware when using sanctum?

Tell me, I use sanctum for authorization, I decided to add my own middleware, which should check Auth::user() However, with such a call:

Route::middleware('auth:sanctum')->middleware('activated')->group(function () {
    Route::get('/name', function (Request $request) {
        return response()->json(['user' => auth()->user()]);
    });
});


Auth::user() inside activated returns null;

However, if you use this middleware for a specific route, and not for a group, everything works:

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/name', function (Request $request) {
        return response()->json(['user' => auth()->user()]);
    })->middleware('activated');
});


But this is inconvenient, because there can be hundreds of routes. As far as I understand, the problem is in the middleware call order.

I tried to do this in Http/Kernel.php:

protected $middlewarePriority = [
    \App\Http\Middleware\Authenticate::class,
    \App\Http\Middleware\CheckUserActivation::class
];


Does not give a positive effect.

How to run activated after auth:sanctum to have Auth::user() inside it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question