Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current user in Laravel API using Passport?

I am using passport package for Laravel API Authentication. When I post data I get error:

401 Unauthorized","error":{"error":"Unauthenticated."}.

I use Auth::user()->id; to get current user id.

How to solve this error?

like image 966
Karthik Avatar asked Jan 24 '18 08:01

Karthik


2 Answers

This code helped me:

auth()->guard('api')->user()

for shortline syntax you can use something like this:

auth('api')->user()
like image 170
Gautam Patadiya Avatar answered Sep 22 '22 02:09

Gautam Patadiya


You can get current user in laravel api using passport as below:

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

but you are getting 401 Error that means either you are not passing access_token in Authorization header or your access_token has expired so you have to refresh the token,

You have to pass access_token in Authorization header which you have got after successfully logged in.

Your user route is protected by passport so When calling routes that are protected by Passport, your application's API consumers should specify their access token as a Bearer token in the Authorization header of their request.

For example, when using the Guzzle HTTP library you can pass it as below:

$response = $client->request('GET', '/api/logout', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);

from the doc laravel passport passing access token

like image 22
Haritsinh Gohil Avatar answered Sep 22 '22 02:09

Haritsinh Gohil