Framework: Illuminate\Auth\TokenGuard Auth:user() is null

Created on 9 Jan 2016  路  12Comments  路  Source: laravel/framework

Hi,

I'm struggling with implementing the token based authentication scheme.
Using a clean Laravel 5.2 install and a php artisan make:auth I create the following test route:

// routes.php
Route::get('/home-index',   ['uses' => 'HomeController@index',      'middleware' => ['web']]);
Route::get('/home-web',     ['uses' => 'HomeController@index',      'middleware' => ['web', 'auth:web']]);
Route::get('/home-api',     ['uses' => 'HomeController@index',      'middleware' => ['api', 'auth:api']]);

The HomeController looks like

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    public function index()
    {
        dd(Auth::user());
    }
}
  1. /home-index works as I expect, returns the logged in user, or null, if I'm not logged in
  2. /home-web works as I expect, returns the logged in user, or redirect me to the login page
  3. /home-api doesn't work as I expect:

    1. while it redirects me to the login page if I don't pass a ?api_token=xxxxx,

    2. if I'm using /home-api?api_token=xxxxx it returns null (my users table has a column called api_token, and I'm using an existing token)

The only way I could retrieve the user with the corresponding api_token is to use dd(Auth::guard('api')->user());, which is not ideal.

So what do I miss here? Is there a more consolidated way to retrieve the authenticated user, without specifying the guard I'm using?

Thanks, Sebi

Most helpful comment

I'd expect the guard AuthManager uses to be the same as the one specified in my auth middleware, what would be the situation where you wouldn't want that to happen?

@tlaverdure you can add

if (!is_null($guard)) {
    Auth::shouldUse($guard);
}

in the Authenticate middleware to automatically change the guard if it's not the default.

Info: Auth::shouldUse

All 12 comments

The guard used in middlewares is not applied on Auth when accessing these controllers. The specification of guard() is a must if you are not using the default guard, IMO.

Yeah, I've seen that here, no matter which guard is used, it's not taken into consideration there: https://github.com/laravel/framework/blob/5.2/src/Illuminate/Auth/AuthManager.php#L244
Not sure if it's a bug, or by design, I'd be very happy to see this working, it would make things way more easy.

Anyhow, the documentation is a bit confusing, as it suggests that:

For example, Laravel ships with a session guard which maintains state using session storage and cookies and a token guard, which authenticates users using a "API token" that is passed with each request.

You may access the authenticated user via the Auth facade: $user = Auth::user();

Thanks, Sebi

@sebestenyb Actually it does. Take a look at these lines: https://github.com/laravel/framework/blob/5.2/src/Illuminate/Auth/AuthManager.php#L66-L79
When you give a specific guard, AuthManager will resolve it to Session or Token driver.
Method __call is clearly stated as

    /**
     * Dynamically call the default driver instance.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     */

When I'm saying documentation, I refer to https://laravel.com/docs/5.2/authentication#retrieving-the-authenticated-user.

And when I'm saying the documentation is confusing, I'm referring that it states

a token guard, which authenticates users using a "API token"

and then later

You may access the authenticated user via the Auth facade: $user = Auth::user();

But actually it's not possible to retrieve the authenticated user using $user = Auth::user(), if it's authenticated via the TokenGuard.

Anyway thanks for looking at this. As far as I understand, it's Working as Intended :)

Cheers, Sebi

I was talking about your first part. I agree that the organization of Authentication Guard documentation is not really good. It seems very "fragmented".
You're welcome ;)

+1

This doesn't appear to be a "bug", though we are of course open to PRs to improve the docs as always,

One more comment, you can't use policies to authorise users authenticated via the TokenGuard:

Illuminate\Foundation\Auth\AccessAuthorizesRequests::authorize
Illuminate\Auth\Access\Gate::authorize
Illuminate\Auth\Access\Gate::raw
Illuminate\Auth\Access\Gate::resolveUser
Auth::user()

API Token Authentication in Laravel 5.2
By JacobBennett

https://gistlog.co/JacobBennett/090369fbab0b31130b51

I ran into this today as I was trying to use $request->user(); with the token guard. Is there a cleaner or default way to do this? Currently just placing this in App\Middleware\Authenticate

public function handle($request, Closure $next, $guard = null)
{
    ...

    //Set $request->user() to Auth::guard('api')->user();
    if (Auth::guard($guard)->user() && $guard == 'api') {
        $request->setUserResolver(function () use ($guard) {
            return Auth::guard($guard)->user();
        });
    }

   ...
}

Using $request->user() seems like it would limit the if/else statements needed when switching guards.

I'd expect the guard AuthManager uses to be the same as the one specified in my auth middleware, what would be the situation where you wouldn't want that to happen?

@tlaverdure you can add

if (!is_null($guard)) {
    Auth::shouldUse($guard);
}

in the Authenticate middleware to automatically change the guard if it's not the default.

Info: Auth::shouldUse

hello,
this is my Routes.php

Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/login',  'Userscontroller@user_login');
});

When I run in post man , I get error as

' <' unexpected

where am I lacking?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lzp819739483 picture lzp819739483  路  3Comments

jackmu95 picture jackmu95  路  3Comments

JamborJan picture JamborJan  路  3Comments

progmars picture progmars  路  3Comments

gabriellimo picture gabriellimo  路  3Comments