Karthik
Karthik

Reputation: 5757

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?

Upvotes: 12

Views: 24572

Answers (6)

Ali
Ali

Reputation: 57

Also you can use this:

    $user = Auth::guard('api')->user();

Upvotes: 0

Gautam Patadiya
Gautam Patadiya

Reputation: 1412

This code helped me:

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

for shortline syntax you can use something like this:

auth('api')->user()

Upvotes: 19

Evans M.
Evans M.

Reputation: 1961

You need to follow a few steps and ensure they are all correct

  1. Follow all the setup instruction for Laravel Passport and ensure the backend side is working correctly
  2. When making your requests ensure you have passed a correct access token via the authorization header Authorization: Bearer xxx-token-here-xxx

Once you have confirmed the above is done correctly ensure your routes are protected by the api guard. If your routes are not protected then passport won't secure them

Below example using a group of routes

Route::group(['prefix' => 'v1',  'middleware' => 'auth:api'], function()
{
    Route::get("articles","ArticleController@read");
    Route::post("articles","ArticleController@create");
});

Upvotes: 0

Haritsinh Gohil
Haritsinh Gohil

Reputation: 6272

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

Upvotes: 2

Tung Nguyen
Tung Nguyen

Reputation: 263

When you use Auth::user()->id in your function's body. You have not logged in before. Please call login api first to get token then set it to the next API call.

Upvotes: 0

Rahul Reghunath
Rahul Reghunath

Reputation: 1276

The simplest format is auth('api')->user();

Upvotes: 7

Related Questions