I was using Laravel's built-in api token authentication before but I wanted to provide multiple api tokens for different clients and with Laravel 7.x, I'm trying to migrate to Laravel Sanctum.
API seems authenticates user without any problem but when I try to get user data with Auth::user();
, it returns null. Also Auth::guard('api')->user();
returns null too.
What should I use as Auth guard? Or is it correct way to get user data based on provided token?
Thank you very much....
First, route through the sanctum auth middleware. Route::get('/somepage', 'SomeController@MyMethod')->middleware('auth:sanctum'); Then, get the user.
Laravel JWT authentication vs. Sanctum offers both session-based and token-based authentication and is good for single-page application (SPA) authentications. Passport uses JWT authentication as standard but also implements full OAuth 2.0 authorization.
First, route through the sanctum auth middleware.
Route::get('/somepage', 'SomeController@MyMethod')->middleware('auth:sanctum');
Then, get the user.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function MyMethod(Request $request) {
return $request->user();
}
}
auth()->user()
is a global helper, Auth::user()
is a support facade, and $request->user()
uses http. You can use any of them.
For a quick test, try
Route::get('/test', function() {
return auth()->user();
})->middleware('auth:sanctum');
Be sure to send your token in a header like so:
Authorization: Bearer UserTokenHere
auth('sanctum')->user()->id
auth('sanctum')->check()
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