Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting user data with Laravel Sanctum

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

like image 365
she hates me Avatar asked Jul 16 '20 19:07

she hates me


People also ask

How do you get Auth user in laravel Sanctum?

First, route through the sanctum auth middleware. Route::get('/somepage', 'SomeController@MyMethod')->middleware('auth:sanctum'); Then, get the user.

Does laravel sanctum use JWT?

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.


Video Answer


2 Answers

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
like image 184
Gavin Avatar answered Sep 19 '22 23:09

Gavin


auth('sanctum')->user()->id
auth('sanctum')->check()


without middleware, you could use these.
like image 36
Parsa Samandizadeh Avatar answered Sep 16 '22 23:09

Parsa Samandizadeh