laravel passport: Request user() returning null outside auth:api middleware, and inside returning user object

When the auth middleware is not provided, or is provided without specifying the guard, the default guard is used to determine the user. Unless you have changed this in your config/auth.php file, the default guard is the web guard.

So, when you go to a route that is not protected by a specific auth middleware, the user that is loaded is the one provided by the web guard.

Therefore, even though you may be sending the bearer token to use a specific user, the web guard doesn't know anything about that, and since you have no user logged in via the web guard, you are getting a null user.

You've got four options:

  1. Make sure the route is protected by the auth:api middleware, which specifies the api guard. This, however, will not allow guests to access the url.

  2. Change your default guard to api in your config/auth.php file. This is probably not what you want to do, especially if you do have normal web users.

  3. Tell the request you want the user from the api guard. The $request->user() method takes a guard as an argument, so if you do $request->user('api'), it will retrieve the user using the api guard.

  4. Get the user from the api guard directly: auth()->guard('api')->user().


The auth middleware is the one returning the user. auth:api just indicates to use the API guard. In the source code of laravel, the file vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php line 62, the function shouldUse is the one setting the Auth::user() object. Check out also vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php shouldUse function

Tags:

Php

Laravel