In api.php
routes file below, there are public routes and private routes:
Route::group(['namespace' => 'API'], function() {
// Public routes (auth not required)
Route::group([], function() {
Route::get('/testauth1', 'TestController@testauth1');
// more public routes...
});
// Private routes (auth required)
Route::group(['middleware' => 'auth:api'], function() {
Route::get('/testauth2', 'TestController@testauth2');
// more private routes...
});
});
In the TestContoller
these are the 2 methods called above:
class TestController extends Controller {
public function testauth1(\Request $request) {
// return auth()->user(); // does not return user
return $request->user(); // does not return user
}
public function testauth2() {
return auth()->user(); // returns user
}
}
Since the private route group has the auth:api
middleware, we will ensure the user is authenticated by checking the token supplied in the Authorization Bearer
header. Only if a valid token is present will the private routes be rendered to the authenticated user. This is why TestController@testauth2
returns the auth user correctly.
Now, anyone can access the public routes, with or without token. If there is no token supplied in the Authorization Bearer
header, then we'll have no authenticated user, which makes sense. This is why TestController@testauth1
does not return an auth user. However, when a logged in user accesses /testauth1
public route, they provide their token in the Authorization Bearer
header and therefore should be returned in TestController@testauth1
if not with auth()->user()
at least with the $request->user()
but we can't seem to access the user with their supplied token in that method.
Any idea how we can access the valid token user in all public route methods?
A Manual Laravel Authentication Test: Creating a User To log in, we'll send a POST request to /api/login . If our credentials are correct, we will also get a token from our Laravel login API this way. The authorization token we get returned from this request we can use when we want to access a protected route.
Laravel includes built-in authentication and session services which are typically accessed via the Auth and Session facades. These features provide cookie-based authentication for requests that are initiated from web browsers. They provide methods that allow you to verify a user's credentials and authenticate the user.
Auth::check() defers to Auth::user() . It's been that way since as long as I can remember. In other words, Auth::check() calls Auth::user() , gets the result from it, and then checks to see if the user exists. The main difference is that it checks if the user is null for you so that you get a boolean value.
Pass the api
guard as a parameter to fetch the authorized user without the middleware protecting the request.
$request->user('api');
// Or
auth('api')->user();
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