Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

knubbe's avatar
Level 36

Impersonate user with Laravel Passport token

I have a service which receives a request with user_id as a part of header. Only users / consumers with proper token can use this service but I also need additional feature impersonation that I need to impersonate user with id of the header user_id and this user should act as Auth::user() for further consuming api because there is some endpoints that returns Auth::user()->some_relation. Is that possible and hot to do it?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To implement user impersonation with Laravel Passport, you can follow these steps:

  1. Validate the Request: Ensure that the request is coming from a user with the proper permissions to impersonate another user.

  2. Find the User to Impersonate: Retrieve the user you want to impersonate using the user_id from the request header.

  3. Generate a Token for the Impersonated User: Create a new access token for the user you want to impersonate.

  4. Set the Impersonated User as Authenticated: Use the generated token to authenticate the impersonated user for the current request.

Here's a code example to illustrate these steps:

use Illuminate\Http\Request;
use Laravel\Passport\Token;
use Laravel\Passport\Passport;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

public function impersonate(Request $request)
{
    // Step 1: Validate the request
    $request->validate([
        'user_id' => 'required|exists:users,id',
    ]);

    // Step 2: Find the user to impersonate
    $userToImpersonate = User::findOrFail($request->header('user_id'));

    // Step 3: Generate a token for the impersonated user
    $tokenResult = $userToImpersonate->createToken('Impersonation Token');
    $token = $tokenResult->accessToken;

    // Step 4: Set the impersonated user as authenticated
    Auth::setUser($userToImpersonate);

    // Optionally, you can return the token to the client
    return response()->json([
        'token' => $token,
        'user' => $userToImpersonate,
    ]);
}

Important Considerations:

  • Security: Ensure that only authorized users can perform impersonation. You might want to add additional checks to verify that the requesting user has the necessary permissions.

  • Token Management: Consider how you will manage and revoke these impersonation tokens. You might want to set a short expiration time for these tokens.

  • Audit Logging: It might be useful to log impersonation actions for auditing purposes, so you can track who impersonated whom and when.

By following these steps, you can implement a user impersonation feature using Laravel Passport.

Please or to participate in this conversation.