Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate user without auth:api middleware in laravel 5.3?

I have a public route that any user can access it. (/timeline).
In this action if user is authenticated, I must show him if he has liked the post.
If the route has auth:api middleware I can get authenticated user using $request->user(), but if I don't use auth:api middleware I can't check if user is authenticated even if user sends correct access_token.
How can I check if access_token is correct without middleware and authenticate user in controller?

like image 584
Ali Farhoudi Avatar asked Feb 27 '17 09:02

Ali Farhoudi


People also ask

How do I authenticate users in Laravel?

Just run php artisan make:auth and php artisan migrate in a fresh Laravel application. Then, navigate your browser to http://your-app.test/register or any other URL that is assigned to your application. These two commands will take care of scaffolding your entire authentication system!

How do I use Auth API middleware in Laravel?

Please run php artisan make:middleware UserAccessible on your terminal. After run above artisan command, you will see generated a file named UserAccessible. php in the App/Http/Middleware folder. Route::group(['middleware' => ['auth:api', 'user_accessible']], function () { // your protected routes. });

How do you check authentication in middleware?

try it : if (Auth::check()) { // The user is logged in... } Make sure the StartSessions middleware is enabled before your middleware. If you haven't started sessions before calling Auth::user() , it will return null.


Video Answer


1 Answers

You can pass the guard to your method to check if the user is logged in with a particular guard.

$request->user('api');

EDIT

I just want to extend my original answer.

Using $request->user() is exactly the same as using \Auth::user().

When you retrieve the authenticated user, Laravel will default the guard from your config file auth.defaults.guard (web in a fresh install).

So when you called $request->user() it was actually $request->user('web').

When you use auth:api, Laravel will then use the api guard as the default.

That's why it worked when using auth:api but didn't when using default guard.

To solve your issue, you can either call $request->user('api') if you have an Illuminate\Http\Request instance or directly \Auth::guard('api')->user() using the Auth facade.

like image 114
Elie Faës Avatar answered Sep 22 '22 17:09

Elie Faës