iamamirsalehi's avatar

Get user by token - sanctum

Hi there, I have a token like 1|bTNlKViqCkCsOJOXWbtNASDKF7SyHwzHOPLNH and I wanna find the user by this token.

note: I can not use auth()->user in a specific controller. thanks in advance

1 like
10 replies
CorvS's avatar
CorvS
Best Answer
Level 27

@iamamirsalehi If you check Sanctum's source code you can see that SHA256 is used to hash the tokens inside the database and how Sanctum fetches a token from the database. You could also just use where and query for the hashed token directly.

https://github.com/laravel/sanctum/blob/2.x/src/PersonalAccessToken.php (See findToken)

$token = PersonalAccessToken::where('token', $hashedToken)->first();

After fetching the token you can simply use $token->tokenable to get the user the token belongs to.

$user = $token->tokenable;
8 likes
luisangeldev's avatar

Other option in Laravel 8 can be

use Laravel\Sanctum\PersonalAccessToken;

$token = PersonalAccessToken::findToken($hashedTooken);

now we can get the user data

$user = $token->tokenable;
8 likes
ryan_'s avatar

You can just use

$user =  auth('sanctum')->user()  
14 likes
aarontharker's avatar

even easier still, as long as your route has passed through the sanctum middleware you can just use,

$user = $request->user();
3 likes

Please or to participate in this conversation.