Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Access the authenticated user inside a middleware

Hello,

I need to refresh the expiration date for the Sanctum API token.

So I have created a middleware with this code.

$request->user()->currentAccessToken()->forceFill([
    'expires_at' => now()->addHour(),
])->updated();

I'm using the middleware for all API routes and I have placed it after the auth:sanctum middleware to be sure that the authentication has been done.

Route::prefix('/v1')->middleware(['auth:sanctum', RefreshApiTokenExpirationMiddleware::class])->group(function () {

But I get an error saying that $request->user() is null.

Why ?

Any idea ?

Thanks for your help.

V

0 likes
10 replies
vincent15000's avatar

@Nakov Hmmm ... no no ... the middleware is to change the expired_at field each time a request is done to the server.

1 like
Nakov's avatar

@vincent15000 not sure if that's a solution.. it will work if there is a user, but what if it is null as the case you had above. Which I am not sure why that can be, other that you have multiple guards implemented so you have to specify the custom guard like this $request->user('api') as an example.

I tried it myself in an app that I have using sanctum, and the user is there for me, I used the log to check if it will print something.

1 like
Nakov's avatar

@vincent15000 That can't be truth. I just removed the token, and tried to access the route, there is nothing in the log.. even adding a simple message does not show.

Anyway, I would rather use Auth::check() and then redirect the user to another page, rather then allowing a route from the group to be accessed even without a user being available.

Because that middleware should not run at all if there is no authenticated user, same with routes in the group..

From what you are saying, that means that even if the user is null and the middleware is still running, then the routes in the groups should run as well, which means no security at all.

1 like
vincent15000's avatar

@Nakov Yes that's true, but I think that I just don't know where to put the middleware in the new Laravel version (11) in comparison with the previous versions where it was easy to order the middlewares as needed.

Snapey's avatar
Snapey
Best Answer
Level 122

remember where you put the middleware in the stack is important.

1 like

Please or to participate in this conversation.