添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Get user from request always returns null (only Auth::guard('api') works) #237

@DanielOlarte

Description

Hello everyone

I have been moving my API to Laravel 5.3 and Passport, I'm creating the whole authentication and authorization flow, and when I add the middleware of the API in my route, like this:

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

On the auth.php file, I have this:

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',

Also, the middleware for auth is:
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,

In the RouteServiceProvider, I have this:

Route::group([
            'namespace' => $this->namespace,
            'middleware' => 'api',
            'prefix' => 'v1',
        ], function ($router) {
            require base_path('routes/api.v1.php');

And the API middleware group is:

    protected $middlewareGroups = [
        'api' => [
            'throttle:100,1',
            'bindings'

In my AuthServiceProvider, I followed some suggestions to add this:

        Passport::tokensExpireIn(Carbon::now()->addDays(15));
        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));

But, the weird thing is that I managed to pass the middleware, but the method $request->user() is always null, I tried with Password Grant and Personal Access Clients.

Then, I'm trying to use Scopes, but I can't pass them because of this issue, then, my only idea for the moment is creating a custom middleware that uses Auth::guard('api')->user() which works without issues.

Did I miss something on this?

Thanks