简体   繁体   中英

Retrieve user by Sanctum plainTextToken

How to retrieve the 'logged in' user from a Sanctum token.

For logging in I have the following method

public function login(Request $request)
{
    if (Auth::attempt($request->toArray())) {

        /* @var User $user */
        $user = $request->user();

        $token = $user->createToken('web-token')->plainTextToken;

        return response()->json([
            'user' => $user,
            'token' => $token,
        ], Response::HTTP_OK);
    }
}

Now for logging out I use a custom method.

public function logout(Request $request)
{
    dd($request->user()); // <- Always returns null
}

I want to revoke the token, but I don't know how to retrieve the currently logged in user. Obviously for logging out I send the Authorization header with the Bearer and plainTextToken as value.

for sure you have first add token in bearer token

and to get user out of sanctum middleware now token is optional

$user = auth('sanctum')->user();

than log out

if ($user) {
    $user->currentAccessToken()->delete();
}

note: this delete only current token

if u need all tokens use

foreach ($user->tokens as $token) {
     $token->delete();
}

If you don't use the default Sanctum middleware, you can get the user from the plain text token as follow:

use \Laravel\Sanctum\PersonalAccessToken;

/** @var PersonalAccessToken personalAccessToken */
$personalAccessToken = PersonalAccessToken::findToken($plainTextToken);

/** @var mixed $user */
$user = $personalAccessToken->tokenable;

simply add the route within middleware('auth:sanctum') grouped routes then from inside the targeted function you can get user like this auth()->user() or if you just want to log out the user you can revoke token like this $request->user()->currentAccessToken()->delete();

Since you're sending the bearer/token to the Logout url you can try to override the logout function of the AuthenticatesUsers :

    /**
* Log the user out of the application.
*
* @param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
    $this->guard()->logout();

    $request->user()->tokens()->delete();

    return redirect('/');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM