Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Illuminate\Auth\TokenGuard Auth:user() is null #11782

Closed
sebestenyb opened this issue Jan 9, 2016 · 12 comments
Closed

Illuminate\Auth\TokenGuard Auth:user() is null #11782

sebestenyb opened this issue Jan 9, 2016 · 12 comments

Comments

@sebestenyb
Copy link

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

@sebestenyb sebestenyb changed the title Illuminate\Auth\TokenGuard Illuminate\Auth\TokenGuard Auth:user() is null Jan 9, 2016
@GrahamCampbell GrahamCampbell reopened this Jan 9, 2016
@hiendv
Copy link
Contributor

hiendv commented Jan 10, 2016

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.

@sebestenyb
Copy link
Author

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

@hiendv
Copy link
Contributor

hiendv commented Jan 11, 2016

@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
     */

@sebestenyb
Copy link
Author

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

@hiendv
Copy link
Contributor

hiendv commented Jan 11, 2016

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 ;)

@paulocastellano
Copy link

+1

@GrahamCampbell
Copy link
Member

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

@sebestenyb
Copy link
Author

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()

@roshimon
Copy link

API Token Authentication in Laravel 5.2
By JacobBennett

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

@tlaverdure
Copy link
Contributor

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.

@3onyc
Copy link
Contributor

3onyc commented Jun 19, 2016

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

@BhavinShah2010
Copy link

BhavinShah2010 commented Jul 4, 2016

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants