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.
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