I am using Passport to log in users to a Laravel API endpoint, users get authenticated using their social accounts (google, facebook) using laravel-socialite package.
the workflow of logging users in and out works perfectly (generating tokens…Etc). The problem is I have a controller that should return data based on whether there is a user logged in or not.
I do intercept the Bearer token from the HTTP request but I couldn’t get the user using the token (I would use DB facade to select the user based on the token but I am actually looking whether there is a more clean way already implemented in Passport)
I also don’t want to use auth:api middleware as the controller should work and return data even if no user is logged in.
this is the api route:
Route::get("/articles/{tag?}", "ArticleController@get_tagged");
this is the logic I want the controller to have
public function get_tagged($tag = "", Request $request)
{
if ($request->header("Authorization"))
// return data related to the user
else
// return general data
}
2
Answers
Assuming that you set your api guard to passport, you can simply call
if (Auth::guard('api')->check())
to check for an authenticated user:This would trigger the Laravel authentication checks in the same way as auth:api guard, but won’t redirect the user away. In fact, the redirection is done by the
Authenticate
middleware (stored invendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php
) upon the failure of the authentication checking.Beware that if you don’t specify the guard to use, Laravel will use the default guard setting in the
config/auth.php
file (usually set to web on a fresh Laravel installation).If you prefer to stick with the Auth facade/class you can as well use
Auth::guard('api')->user()
instead or the request object.thanks to @mdexp answer
In my case I can resolve my problem with using
In my controller.