php 55 lines · 8 steps

How user impersonation works in Laravel

A service that lets an authorized admin log in as another user while remembering how to switch back.

Explained by highlit
1<?php
2 
3namespace App\Services;
4 
5use App\Models\User;
6use Illuminate\Support\Facades\Auth;
7use Illuminate\Support\Facades\Session;
8use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
9 
10class Impersonation
11{
12 protected const SESSION_KEY = 'impersonator_id';
13 
14 public function start(User $target): void
15 {
16 $current = Auth::user();
17 
18 if (! $current->can('impersonate', $target)) {
19 throw new AccessDeniedHttpException('You may not impersonate this user.');
20 }
21 
22 if ($this->isImpersonating()) {
23 throw new \LogicException('Already impersonating a user.');
24 }
25 
26 Session::put(self::SESSION_KEY, $current->getAuthIdentifier());
27 
28 Auth::guard('web')->login($target);
29 Session::regenerate();
30 }
31 
32 public function stop(): void
33 {
34 if (! $this->isImpersonating()) {
35 return;
36 }
37 
38 $original = User::findOrFail(Session::pull(self::SESSION_KEY));
39 
40 Auth::guard('web')->login($original);
41 Session::regenerate();
42 }
43 
44 public function isImpersonating(): bool
45 {
46 return Session::has(self::SESSION_KEY);
47 }
48 
49 public function impersonator(): ?User
50 {
51 return $this->isImpersonating()
52 ? User::find(Session::get(self::SESSION_KEY))
53 : null;
54 }
55}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Stash the original identity in the session before swapping so you always have a route back.
  2. 2Gate sensitive actions behind an authorization policy check before touching any state.
  3. 3Regenerating the session on every auth switch prevents session fixation across identities.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How user impersonation works in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code