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?
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!
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. });
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With