Auth::user(); doesn't returns users, using passport

Viewed 252

I have situation about returning users from DB. In my controller I am trying it like below:

UPDATED:

NOTE: for clear misunderstanding. Actually I am logged in as a user. No problem with that part. But it looks like auth:: doesn't understand that and when I try to retrieve users. it's redirecting me to login's endpoint...

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;

class UsersController extends Controller
{
    public function getUser(){

        $users = Auth::user();
        dd($users);
    }
}

And about the api route:

Route::group(['middleware' => 'auth:api'], function() {

    Route::post("logout", "Api\AuthController@logout");

    /* User */
    Route::get('/user', 'Api\UsersController@getUser');

});


Route::group(["prefix" => "v1"], function(){

    /* Auth */
    Route::post("login", "Api\AuthController@login")->name("login");
    Route::post("register", "Api\AuthController@register");

});

Here is the thing. If I use my UserController route outside the middleware:api then endpoint is returns null. And if use it inside the middleware it redirects me to my login's endpoint. Because of the "->name('login')"

In the end I can't return the users. Additionally this is what config/auth looks like.

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

By the way before asked. I tried to change guard's web to api but nothing is changed.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Is there anyone have better understanding on this situation. How can I return users with using passport? Do I missing something here?

2 Answers

Apparently, the problem is with the request header. Only a logged in user can call /api/user endpoint with an access_token in the request header.

Request header will have this pair

Authorization: Bearer eyJ0eXAiOiJKV1..........

Nothing to do in laravel part, as it's working as expected.

If you are using Laravel Passport. Let's read and make your step same in document: https://laravel.com/docs/5.8/passport

From your API request, need to pass the access_token to backend.

Hoping you can resolve that issue!

Related