# Impersonation

Source: https://keyringphp.com/docs/0.x/impersonation

## Introduction

Impersonation lets support staff or an administrator sign in as another user, see the app as they do, then go back to their own account. Keep these in mind:

- Nobody may impersonate anyone until you say who may.
- The impersonated session starts with nothing the impersonator proved. It ends after an hour, or sooner if the user ends it.
- While it lasts, Keyring refuses every change to how the user signs in.

## Turning It On

Turn the feature on, then migrate.

```php
'features' => [
    // ...
    Features::impersonation(),
],
```

```bash
php artisan keyring:install
php artisan migrate
```

The migration adds three columns to `keyring_sessions`, which only Keyring's `database` session registry driver (`sessions.driver`) needs. The `cache` driver needs no migration. Without the columns, the first start throws `Keyring\Exceptions\MissingMigration`.

Starting needs two factors proved in the last 15 minutes. If your app only signs in with a password, ask for a recent password instead:

```php
'impersonation' => [
    // ...
    'middleware' => ['keyring.fresh:15m'],
],
```

An empty list asks for nothing more.

> [!WARNING]
> Every server must share the `cache.limiter` store (or your default store). An impersonation's end is claimed there, so servers with separate caches can each log it.

## Who May Impersonate Whom

Register a callback that says who may sign in as whom. Until you do, nobody may.

```php
use App\Models\User;
use Keyring\Facades\Keyring;

Keyring::allowImpersonationWhen(fn (User $impersonator, User $user) => $impersonator->isAdmin() && ! $user->isAdmin());
```

Whatever the callback says, Keyring refuses yourself, an account outside its guard, a user who may not [sign in](https://keyringphp.com/docs/0.x/sign-in-flow#who-may-sign-in), and a second impersonation while one runs. A [risk](https://keyringphp.com/docs/0.x/risk) lock doesn't stop one, so refuse locked accounts in the callback if support shouldn't reach them.

> [!WARNING]
> The callback runs on every request of a running impersonation, and on those the signed-in user is the one being impersonated. `auth()->user()`, `$request->user()` and `Gate::allows()` would end it on the first request.

A no from the callback ends the impersonation and goes back to the impersonator's account. Ask about the impersonator instead:

```php
use Illuminate\Support\Facades\Gate;

Keyring::allowImpersonationWhen(fn (User $impersonator, User $user) => Gate::forUser($impersonator)->allows('impersonate', $user));
```

During an impersonation, a throwing callback counts as a no and is reported. Before starting, it's a `500` unless something catches it.

`Keyring::allowsImpersonation()` shows a button only when it would work:

```blade
@if (Keyring::allowsImpersonation(auth()->user(), $user))
    <form method="POST" action="{{ route('keyring.impersonation.store', $user) }}">
        @csrf
        <button>Sign in as {{ $user->name }}</button>
    </form>
@endif
```

`Keyring::impersonationRefusal()` takes the same two users and returns why not, or `null` when they may. It and `allowsImpersonation()` throw if the callback does.

## Routes

With the feature on, Keyring adds two routes. Neither answers `GET`, and both get the `web` middleware and its CSRF check, so a link can't start or stop one.

| Method | URI | Name | Does |
|---|---|---|---|
| `POST` | `/impersonate/{user}` | `keyring.impersonation.store` | Signs in as the user with that ID. |
| `POST`, `DELETE` | `/impersonate` | `keyring.impersonation.destroy` | Stops, and goes back. |

These are Keyring's paths. A route of your own at either path needs to move or go first.

### Starting

From the browser package, call `impersonate()` with the user's ID:

```ts
import { impersonate } from '@keyringjs/keyring'

await impersonate(user.id)     // { status: 'impersonation-started', redirect: 'https://example.com/dashboard' }
```

One who hasn't proved two factors in the last 15 minutes is [sent to confirm](https://keyringphp.com/docs/0.x/step-up), with a `423` for JSON clients. One with no second factor goes to [`enrollment_url`](https://keyringphp.com/docs/0.x/configuration#account-changes-and-enrollment), or gets a `403`. A refusal is always a `403`, including for an ID nobody has, so the answer doesn't reveal which accounts exist. JSON clients get `{"status": "impersonation-refused", "message": "You can't sign in as that user."}`.

Success goes to `impersonation.redirect_url`, `home` by default. Load the page in full afterwards, so nothing from the other account stays on screen.

### Stopping

Stop with a plain form, or call `stopImpersonating()` from the browser package:

```blade
<form method="POST" action="{{ route('keyring.impersonation.destroy') }}">
    @csrf
    <button>Back to my account</button>
</form>
```

A successful stop answers `impersonation-ended` and goes to `impersonation.return_url`, `home` by default. A second stop, from a stale tab say, is a `409` with `not-impersonating`. If the impersonator's session has ended meanwhile, a JSON client gets a `401`, and a page visit goes to login with `signed-out`. `stopImpersonating()` resolves with the status for both `409`s and throws for the `401`. See the [status table](https://keyringphp.com/docs/0.x/headless#where-each-answer-goes).

## From Your Own Code

Your controllers can call the same methods. Keyring's start and stop, as your own routes:

```php
use App\Models\User;
use Illuminate\Http\Request;
use Keyring\Exceptions\ImpersonationRefused;
use Keyring\Facades\Keyring;

Route::post('/admin/users/{user}/impersonate', function (Request $request, User $user) {
    Keyring::impersonate($request, $user);   // throws ImpersonationRefused

    return redirect('/dashboard');
})->middleware(['auth', 'keyring.not-impersonating', 'keyring:aal2', 'keyring.fresh:15m'])->block();

Route::delete('/admin/impersonation', function (Request $request) {
    if (! Keyring::impersonating($request)) {
        return redirect('/admin/users');   // back already: a second stop, from a stale tab say
    }

    $impersonator = Keyring::stopImpersonating($request);   // null when it signed out instead

    return $impersonator === null ? redirect('/login') : redirect('/admin/users');
})->middleware('auth')->block();
```

- `impersonate()` checks who may, not how the request arrived. Keep the `POST`, the same middleware and `->block()`. Without the block, two starts sent together can both succeed. It needs a cache store that supports locks.
- `stopImpersonating()` throws a `LogicException` when nobody is impersonated, so check `impersonating()` first.
- Send `Clear-Site-Data: "cache", "storage"` yourself, and answer Inertia visits with `Inertia::location()`, as Keyring's routes do.
- Uncaught, `ImpersonationRefused` is a `403`. Its `reason` is an `ImpersonationRefusal`:

| Case | Value | Why |
|---|---|---|
| `Disabled` | `disabled` | The feature is off. |
| `NoCallback` | `no_callback` | `allowImpersonationWhen()` was never called. |
| `Self` | `self` | Impersonating yourself. |
| `NotAllowed` | `not_allowed` | The callback said no, or the user may not sign in. |
| `Impersonating` | `impersonating` | Already impersonating someone. |
| `Unregistered` | `unregistered` | The impersonator's session has no record to return to. |
| `NotFound` | `not_found` | Nobody has that ID. Only logged: the thrown reason is `NotAllowed`. |

`disabled` and `no_callback` also write a warning to your log, so a missing setup doesn't look like a no.

`Keyring::impersonating()` tells you whether the session is impersonating someone, `Keyring::impersonator()` returns who (or `null`), and `Keyring::impersonation()` gives what a [banner](https://keyringphp.com/docs/0.x/impersonation#showing-a-banner) needs. `Keyring::user()` and `Auth::user()` are the impersonated user throughout.

## What Happens to the Sessions

Starting gives the browser a new session ID and a record for the user. That record names the impersonator, carries no proof, is never remembered, and lasts no longer than `impersonation.lifetime`. It doesn't count toward the user's [`sessions.max`](https://keyringphp.com/docs/0.x/devices-and-sessions#how-many-sessions).

The impersonator's own session is parked, not ended, and their "remember me" cookies stay as they are.

> [!WARNING]
> Your app's other session data carries over both ways. A role or an "is admin" flag kept in the session shows the impersonator's value on the user's pages, and the impersonator comes back with whatever the user's pages set. Look these up from the signed-in user on each request, or clear them when `ImpersonationStarted` and `ImpersonationEnded` fire.

Keyring doesn't call `Auth::login()`, so Laravel's `Login` and Keyring's `Authenticated` don't fire for the user. Sign-in listeners such as new device emails don't run.

### Going Back

Stopping, or the time limit, returns the browser to the impersonator's session on a new session ID, but only while it's still good: they still exist and may sign in, aren't [held for a new password](https://keyringphp.com/docs/0.x/protected-changes#requiring-a-password-change), haven't changed their password, and their session isn't revoked, expired, or idled out. Otherwise the browser is signed out.

They come back at AAL1 at most, and have to step up again. A page of the user's could have sent the stop, so Keyring keeps only what still falls short of AAL2. A password stays, a second factor is asked for again, and a passkey that verified them alone is forgotten.

Under `sessions.end_on_lapse`, one that signed in above AAL1 doesn't come back. The browser is signed out with `impersonator_session_ended`.

Put admin routes behind `keyring:aal2` or `keyring.fresh`, not `auth` alone. A script on the user's pages that sends the stop is then held at the step-up.

### Signing Out While Impersonating

Sign out with Keyring's `logout` route. It signs the browser out of both sessions, and leaves the user's "remember me" token alone.

```blade
<form method="POST" action="{{ route('logout') }}">
    @csrf
    <button>Sign out</button>
</form>
```

Laravel's `Auth::logout()` also changes that token, which signs out every other browser where the user ticked "remember me". Use `Auth::logoutCurrentDevice()` while impersonating.

## What's Refused While Impersonating

While someone is impersonating, these get a `403`, and `{"status": "impersonating", "message": "..."}` for JSON clients:

- changing the password or email address, or cancelling an email change,
- adding, confirming, renaming, or removing authenticators,
- ending sessions or devices, "sign out everywhere else" included,
- confirming who they are, including identity provider confirms and links,
- verifying an email address, or sending that link again,
- starting another impersonation.

This holds whatever [`changes_middleware`](https://keyringphp.com/docs/0.x/configuration#account-changes-and-enrollment) says. Still allowed: listing the user's sessions and devices, `GET /user/email`, and signing out.

> [!WARNING]
> Routes behind any `keyring:{level}` (`aal1` included, since the impersonated session has no level) or `keyring.fresh` answer `403` while someone is impersonating, and so does `StepUp::unlessMet()`. So `keyring:aal2` on every signed-in page locks the impersonator out. Put step-up only on routes that need it, or leave it out when `Keyring::impersonating()` is `true`.

`keyring.enrolled` and a password hold still let the impersonator through, since only the user can do what those ask.

### Your Own Routes

Put `keyring.not-impersonating` on routes only the user should use:

```php
Route::delete('/account', [AccountController::class, 'destroy'])
    ->middleware(['auth', 'keyring.not-impersonating', 'keyring.fresh:5m']);
```

It answers with the same `403`, and lets everyone else through.

## Showing a Banner

Share `Keyring::impersonation()` with your pages, and show a banner with a way to stop. It's read from the session, so it costs no query.

```php
use Keyring\Facades\Keyring;

public function share(Request $request): array
{
    return [
        ...parent::share($request),
        'impersonation' => fn () => Keyring::impersonation($request),
    ];
}
```

It's `null` when nobody is impersonating. Otherwise it has `impersonator` (`id` and `name`), `startedAt`, `expiresAt` (when it [ends by itself](https://keyringphp.com/docs/0.x/impersonation#the-time-limit)), and `stopUrl`, which is `null` if Keyring's routes aren't registered. The browser package types it as `Impersonation`:

```tsx
import { router, usePage } from '@inertiajs/react'
import type { Impersonation } from '@keyringjs/keyring'

export function ImpersonationBanner() {
  const { impersonation } = usePage<{ impersonation: Impersonation | null }>().props

  if (!impersonation) return null

  return (
    <div role="status">
      You ({impersonation.impersonator.name}) are signed in as this user.
      <button onClick={() => router.delete(impersonation.stopUrl!)}>Stop impersonating</button>
    </div>
  )
}
```

In Blade:

```blade
@if (Keyring::impersonating())
    <div role="status">
        Signed in as {{ auth()->user()->name }}.
        <form method="POST" action="{{ route('keyring.impersonation.destroy') }}">
            @csrf
            <button>Back to my account</button>
        </form>
    </div>
@endif
```

## The Time Limit

Set how long an impersonation may last. `sessions.absolute` caps it.

```php
'impersonation' => [
    'lifetime' => '1h',
],
```

It ends by itself `lifetime` after it started, and the next request goes back. A page visit goes to `impersonation.return_url` with the `impersonation-ended` status, and a JSON request gets a `409` with the same status. Unused for `sessions.idle`, it ends sooner. The impersonator's session has usually idled out too, so the browser is signed out.

## The Sessions List

The impersonated session shows in the user's sessions list, marked with the impersonator's name, and they can end it there:

```json
{
  "id": "9f2c41d0...",
  "name": null,
  "ip": null,
  "device": null,
  "remembered": false,
  "signedInAt": "2026-11-27T09:00:00+00:00",
  "lastActiveAt": "2026-11-27T09:12:00+00:00",
  "expiresAt": "2026-11-27T10:00:00+00:00",
  "current": false,
  "impersonated": true,
  "impersonator": { "name": "Ada Admin" }
}
```

Its browser, IP address, and device are always `null`. To hide it from the list, set `impersonation.show_in_sessions` to `false`. It still ends with their other sessions and still counts in "sign out everywhere else".

## Security Log and Events

Each start and end is logged on both accounts, as `impersonation_started` and `impersonation_ended`, with `impersonator`, `user`, and `role`. An end also has `reason` and `returned`. The user's entries have no IP address or user agent.

A refused start is logged as `impersonation_refused` on the impersonator's account, with `reason` and `user`, at most `security_log.refusals` times per `security_log.refusals_per`.

| Reason | When |
|---|---|
| `stopped` | The impersonator stopped it. |
| `expired` | Its `lifetime` ran out, or the session idled out. |
| `revoked` | It was ended some other way: by the user, signing out everywhere, a password change, or a risk response. Also the user no longer being allowed to sign in, or the callback no longer allowing it. |
| `impersonator_session_ended` | The impersonator's session can't be returned to, so the browser was signed out. Also a session that signed in above AAL1 under `sessions.end_on_lapse`. |
| `lost` | The browser's session no longer held the impersonation, so it was signed out. |
| `signed_out` | The browser signed out while impersonating. |
| `failed` | Starting failed after it was logged. The browser stayed the impersonator's. Logged only. |

Keyring dispatches `ImpersonationStarted` (`impersonator`, `user`, `handle`) and `ImpersonationEnded` (`impersonator`, `user`, `reason`, `returned`, `handle`). `handle` is the session's [handle](https://keyringphp.com/docs/0.x/devices-and-sessions#listing-and-ending-sessions), the same one the sessions list shows. On `ImpersonationEnded`, `impersonator` is `null` once deleted and `user` once it can't be loaded, and `handle` is `null` only when nothing says which session it was. A `failed` start fires neither event. If the browser never returns, only the session's `RegisteredSessionEnded` fires, from the sweep.

No email is sent by default. To keep these entries out of `Keyring::activity()`, set `impersonation.show_in_activity` to `false`. They're still written.

## How It Works

- **Parked session.** Starting parks the impersonator's session with its proof and a hash of their password. Going back restores it only while it's still good and the hash hasn't changed. Any change, even one made in another browser, signs the browser out.
- **One ending.** Only one request ends an impersonation. It alone logs the end and fires `ImpersonationEnded`. The claim lives in `cache.limiter`, and the others get `lost`.
- **Session IDs.** A request that finishes after a start or stop can't save the old session back. A route of your own that rotates the session needs `->block()` too.
- **Failed starts.** A start that can't be logged throws whatever the security log threw, and the browser stays as it was.

## Migrating From Another Package

From `lab404/laravel-impersonate`, `stechstudio/filament-impersonate`, or Nova's impersonation:

| Before | With Keyring |
|---|---|
| `canImpersonate()` and `canBeImpersonated()` on the model | One `Keyring::allowImpersonationWhen()` callback, given both. |
| `GET /impersonate/take/{id}` and `GET /impersonate/leave` | `POST /impersonate/{user}`, and `POST` or `DELETE /impersonate` |
| `$manager->take($from, $to)` and `$manager->leave()` | `Keyring::impersonate($request, $user)` and `Keyring::stopImpersonating($request)` |
| `isImpersonating()`, `@impersonating` | `Keyring::impersonating()` |
| The `impersonate.protect` middleware | `keyring.not-impersonating` |
| `TakeImpersonation` and `LeaveImpersonation` events | `ImpersonationStarted` and `ImpersonationEnded` |
| No time limit | `impersonation.lifetime`, an hour by default |

Some things differ. Going back needs the impersonator's session to still be good, where those packages sign them back in by ID alone. Nothing they proved carries over, so step-up routes are refused while impersonating, and Keyring's security changes are refused without any middleware of yours.

Remove the package's routes, trait, and middleware, register the callback, and swap its Blade directives and route names. Anyone impersonating when you deploy stays signed in as the user, on a session Keyring doesn't know is impersonated, until they sign out.
