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

ChrisPercival's avatar

Impersonating users

Hi All

I have noticed that Taylor has an "impersonating user" feature in Spark.

I am looking to do the same, also from the point of view, to support our users.

I have had a look at Laravel's docs, but I am a little lost on the best way to do it.

Any pointers would be great.

Thanks Chris

0 likes
6 replies
Snapey's avatar

create a middleware that checks for a session variable 'impersonate' and then logs in as that ID

use Closure;
use Illuminate\Support\Facades\Auth;

class Impersonate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(session()->has('impersonate')){
            Auth::onceUsingID(session('impersonate'));
        }

        return $next($request);
    }
}

add this at the end of the web middleware group in kernel.php

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\Impersonate::class,
        ],

Then all you need is an admin function that sets the impersonate value in the admin user's session

  session()->put('impersonate',$user->id);
7 likes
martinbean's avatar
Level 80

@ChrisPercival The way it works in Spark is, an impersonator value is put in the session with the current user’s ID. Spark then logs the requested user in using Auth::login(User::findOrFail($requestedId)).

To stop impersonating, Spark just pulls the impersonating user’s ID from the session and again does an Auth::login(User::findOrFail($impersonatorId)).

3 likes
jamesbuch's avatar

I do it like this for an API, where an admin can switch accounts in the dashboard and retrieve a JWT to impersonate a user and view the state of the app as that user:

public function impersonate()
{
        $credentials = request(['email', 'password']);
        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        // Admin?
        if (! auth()->user()->is_admin) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $user = User::where('email', request('impersonate'))->first();
        if (! $user) {
            // No such user?
            return response()->json(['error' => 'No user with that email'], 404);
        }

        // Get the token, authenticate as this user
        $token = auth()->login($user);
        return $this->respondWithToken($token);
}

Here, I have a flag on the users table, is_admin. This is set for the super user. I use the tymon/jwt-auth package to provide JWT auth for API routes. Easy peasy!

Please or to participate in this conversation.