# Impersonation

Source: https://keyringauth.com/docs/0.x/go/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, as in the PHP package:

- 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.

The routes, JSON, statuses and log entries are the PHP package's, as the [contract suite](https://github.com/keyringauth/keyring/blob/main/contract/README.md) checks them, and the sessions it writes are the PHP package's rows.

## Turning It On

Turn on `Features.Impersonation`, which starts off, and say who may impersonate whom with `AllowImpersonationWhen`:

```go
k := keyring.New[models.User](func(cfg *keyring.Config) {
	cfg.Features.Impersonation = true
}).AllowImpersonationWhen(func(_ context.Context, impersonator, user *models.User) bool {
	return impersonator.IsAdmin && !user.IsAdmin
})
```

`IsAdmin` is a field of your own user type.

The migration that adds the impersonation columns to `keyring_sessions` already runs with Keyring's others, so the table is ready, and sessions a PHP application impersonates on a shared database keep their columns.

Starting needs AAL2 and two factors proved in the last 15 minutes, as the PHP package's default `impersonation.middleware`. In Go that's `Impersonation.Middleware`, a list of middleware values, which `Register` fills in with `RequireAssurance[U]{Level: keyring.AAL2}` and `RequireFreshVerification[U]{Within: 15 * time.Minute}` when you leave it `nil`. For an application that only signs in with a password:

```go
cfg.Impersonation.Middleware = []web.Middleware{
	keyring.RequireFreshVerification[models.User]{Within: 15 * time.Minute},
}
```

An empty list, `[]web.Middleware{}`, asks for nothing more than a signed-in session. The confirm for AAL2 builds on what still counts toward it, as in the PHP package.

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

## Who May Impersonate Whom

Until you call `AllowImpersonationWhen`, nobody may (`no_callback`, with a warning in the application's log). It's given the request's context, the impersonator and then the user, as the PHP closure is given the two users. Whatever it says, Keyring refuses yourself, a user who may not sign in (see [Who May Sign In](https://keyringauth.com/docs/0.x/go/sign-in-flow#who-may-sign-in)), an ID nobody has, a second impersonation, and a session with no record.

It's asked on every request of a running impersonation, so decide from its two users alone, never from `auth.User`, which is the user being impersonated by then. A callback that panics fails a start with a `500`, starting nothing, as a PHP callback that throws. While an impersonation runs, a panic is reported and counts as a no, which ends it.

`k.AllowsImpersonation(r, impersonator, user)` says whether to show a button, and `k.ImpersonationRefusal(r, impersonator, user)` says why not, or `""` when they may:

```go
refusal, err := keyring.From[models.User](r).ImpersonationRefusal(r, admin, user)
// "" when they may, or keyring.RefusalDisabled, RefusalNoCallback, RefusalSelf or RefusalNotAllowed
```

Its values are the PHP package's `ImpersonationRefusal` cases: `disabled`, `no_callback`, `self` and `not_allowed`, in that order. Starting can also be refused as `impersonating` (`RefusalImpersonating`) or `unregistered` (`RefusalUnregistered`), which depend on the session rather than the two users, and an ID nobody has is logged as `not_found` (`RefusalNotFound`) and answered as `not_allowed`. Neither method asks what `Impersonation.Middleware` asks. `err` is a callback that panicked, which `AllowsImpersonation` reports and counts as a no.

An admin without a second factor can still impersonate someone if your callback lets them and `Impersonation.Middleware` doesn't ask for AAL2, since `RequireEnrollment` doesn't stand in front of Keyring's `POST /impersonate/{user}`. If you require a second factor of admins, check it in your callback.

## Routes

| 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. |

They're there while `Features.Impersonation` is on, in the `web` group with its CSRF check, behind `auth.Authenticate`, and take the session lock. Starting is behind `RefuseWhileImpersonating`, `Impersonation.Middleware` and `Limits.Forms` (six a minute).

### Starting

The browser package's `impersonate(user.id)` works unchanged. One who hasn't proved what `Impersonation.Middleware` asks is sent to confirm, with a `423` for JSON. One with no second factor gets `enroll-first`. A refusal is a `403`, the same for every reason:

```json
{ "status": "impersonation-refused", "message": "You can't sign in as that user." }
```

A page visit gets the `403` page with the same message. Success answers `impersonation-started`, going to `Impersonation.RedirectURL`, or `Home` when it's empty:

```json
{
  "status": "impersonation-started",
  "message": "You're now signed in as someone else. Stop impersonating to go back to your own account.",
  "redirect": "http://localhost:8000/dashboard"
}
```

Keyring's start and stop send `Clear-Site-Data: "cache", "storage"`, and an Inertia visit loads the next page in full.

### Stopping

A successful stop answers `impersonation-ended` (`"You're back in your own account."`), with a `redirect` to `Impersonation.ReturnURL`, or `Home` when it's empty. A stop that finds the impersonator's own session over signs the browser out instead, answered as any session that ended.

A second stop, from a stale tab say, is a `409` for JSON, and a page visit goes to `ReturnURL` with the status flashed:

```json
{
  "status": "not-impersonating",
  "message": "You're not signed in as someone else.",
  "redirect": "http://localhost:8000/dashboard"
}
```

## From Your Own Code

Routes of your own start and stop one with `k.Impersonate` and `k.StopImpersonating`, as `Keyring::impersonate()` and `stopImpersonating()`:

```go
package routes

import (
	"go.laravel.com/auth"
	"go.laravel.com/config"
	"go.laravel.com/model"
	"go.laravel.com/routing"
	"go.laravel.com/web"

	keyring "keyringauth.com/go"

	"app/models"
)

func Web(route *routing.Router, _ *config.Config) {
	route.Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {
		route.Post("/admin/users/{user}/impersonate", impersonate).
			Middleware(keyring.RefuseWhileImpersonating{}, keyring.BlockSession{})
		route.Post("/admin/impersonation/stop", stopImpersonating).Middleware(keyring.BlockSession{})
	})
}

func impersonate(r *web.Request) *web.Response {
	user, err := model.Find[models.User](r, r.PathValue("user"))
	if err != nil {
		return web.Fail(err)
	}

	// A refusal is a *keyring.ImpersonationRefusedError, which web.Fail
	// answers as Keyring's route does.
	stepUp, err := keyring.From[models.User](r).Impersonate(r, &user)
	if err != nil {
		return web.Fail(err)
	}
	if stepUp != nil {
		return stepUp // the confirm's 423, or enroll-first: nothing started
	}

	return web.Redirect("/dashboard").WithHeader("Clear-Site-Data", `"cache", "storage"`)
}

func stopImpersonating(r *web.Request) *web.Response {
	k := keyring.From[models.User](r)
	if !k.Impersonating(r) {
		return web.Redirect("/admin/users") // back already: a second stop, from a stale tab say
	}

	// nil when it signed out instead.
	impersonator, err := k.StopImpersonating(r)
	if err != nil {
		return web.Fail(err)
	}
	if impersonator == nil {
		return web.Redirect("/login")
	}

	return web.Redirect("/admin/users").WithHeader("Clear-Site-Data", `"cache", "storage"`)
}
```

Put the start on a `POST` in the `web` group, behind `RefuseWhileImpersonating`, as Keyring's route refuses a second impersonation, and `BlockSession`, so two starts sent at once take turns. `Impersonate` asks what `Impersonation.Middleware` asks first, and returns the answer to send (the `423` naming the confirm page, or `enroll-first`) without starting anything, where the PHP package leaves that to the route's middleware. It returns `nil, nil` once it has started. Send `Clear-Site-Data: "cache", "storage"` yourself, as Keyring's routes do.

A refusal is an `*keyring.ImpersonationRefusedError`, logged on the impersonator's account. Its `Reason` says why, for your own code, and its message and its answer are the same whatever the reason, so `web.Fail(err)` never tells the browser why. Find it with `errors.AsType[*keyring.ImpersonationRefusedError](err)`.

`StopImpersonating` is an error when nobody is being impersonated, so check `Impersonating` first. When it signs the browser out instead of going back, the session is emptied, but Laravel Go has no way to make the guard forget a user without `auth.Logout`, which would change the user's remember token: `auth.User` still returns the impersonated user for the rest of the request. Answer straight away, with a redirect, rather than carry on as them.

`k.Impersonator(r)` loads who is impersonating, or `nil`, as `Keyring::impersonator()`.

## What Happens to the Sessions

As in the PHP package: starting gives the browser a new session ID and a record for the user that names the impersonator and their parked record, at no level, never remembered, on no device, with no address or browser, lasting `Impersonation.Lifetime` at most. The impersonator's session is parked, not ended, and kept from idling out while they're busy. `Authenticated` doesn't fire for the user. The impersonated session neither counts toward `Sessions.Max` nor is ended by it.

Someone's name, for the banner and the sessions list, is their `Name` field (a `string` or `*string`), or else the field of `Config.Username`'s column, standing in for the PHP package's `name` attribute and username. A user type with neither has no name (`null`).

> [!WARNING]
> Your app's other session data carries over both ways, as in the PHP package. Keyring only forgets its own keys, `auth.password_confirmed_at` and the intended URL as the browser changes hands. Look up roles and "is admin" flags from the signed-in user rather than keeping them in the session.

### Going Back

Going back, on a stop, when `Lifetime` runs out, or when the user ends the session, takes the impersonator's record still being good, the impersonator still allowed to sign in, not held for a new password, on the password they had when it started, and under `Sessions.EndOnLapse` a level that hasn't lapsed. They come back on a new session ID and record, at AAL1 at most with nothing counting as fresh, so a second factor is asked for again. Otherwise the browser is signed out. Under `Sessions.EndOnLapse`, one that signed in above AAL1 doesn't come back, and the browser is signed out with `impersonator_session_ended`. The rules are the [PHP package's](https://keyringauth.com/docs/0.x/impersonation#going-back).

"Remember me" goes back with them: both Keyring's `remembered_session` cookie and Laravel Go's `remember_web`, even when the user's password changed while they were impersonated and the guard took its cookie back.

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

### Signing Out While Impersonating

Keyring's `POST /logout` signs the browser out of both sessions, and leaves every remember token as it is: it signs this browser out alone, where it otherwise uses `auth.Logout`.

Your own `auth.Logout` while impersonating also ends the impersonation and the parked session, but it gives the impersonated user a new remember token, which signs out every other browser where they ticked "remember me". Use Keyring's sign out while impersonating. Your own `auth.Login` as someone else, or emptying the session, ends the impersonation and the parked session too, as `signed_out`. So does every sign in of Keyring's on that browser, `k.SignInAs` included, as the PHP package's `SignIn::as()`. Put sign-up routes of your own behind `keyring.Guest[U]{}`, as Keyring's are, so an impersonating browser is sent on rather than signed in as the new account.

## What's Refused While Impersonating

As in the PHP package, these get the `403` `{"status": "impersonating", "message": "You can't do that while you're signed in as someone else."}` (or the `403` page): the confirm routes, every changes route (whatever `ChangesMiddleware` says), `/confirm/sso/redirect` and an identity provider's callback for a link or a confirm, posting a verification link and sending another, cancelling or requesting an email change, and starting another impersonation. A fresh verification or AAL2 asked anywhere else, your own `RequireFreshVerification` and `RequireAssurance` included, answers the same rather than sending the browser to confirm. `RequireEnrollment` and `RequirePasswordChange` let the impersonator through.

Every start, Keyring's route's too, also refuses, as `impersonating`, a start from a session record an impersonation that hasn't ended already parked: a copy of the session from before a start. The PHP package doesn't check this. That impersonation ends as it's refused, so a session left that way isn't refused again.

The risk signals that run on every request skip an impersonated session, as in the PHP package, and `InactiveAccount` doesn't count its use as the owner's. See [Risk](https://keyringauth.com/docs/0.x/go/risk#checkpoints).

### Your Own Routes

Put `keyring.RefuseWhileImpersonating{}` on routes only the user should use, as `keyring.not-impersonating`:

```go
route.Middleware(keyring.RefuseWhileImpersonating{}, keyring.RequireFreshVerification[models.User]{}).Group(func(route *routing.Router) {
	route.Delete("/account", deleteAccount)
})
```

## Showing a Banner

`k.Impersonation(r)` is what a banner needs, as `Keyring::impersonation()`: `nil` when nobody is impersonating, otherwise a `*keyring.ImpersonationBanner`, which serializes as the PHP package's:

```json
{
  "impersonator": { "id": "1", "name": "Admin Ada" },
  "startedAt": "2026-11-27T09:00:00+00:00",
  "expiresAt": "2026-11-27T10:00:00+00:00",
  "stopUrl": "http://localhost:8000/impersonate"
}
```

`expiresAt` is when it [ends by itself](https://keyringauth.com/docs/0.x/go/impersonation#the-time-limit), and `stopUrl` is `null` when Keyring's routes aren't registered. It's read from the session, so it costs no query. Share it with your pages in your Inertia middleware's `Share`:

```go
return inertia.Props{
	"impersonation": keyring.From[models.User](r).Impersonation(r),
}, nil
```

The browser package's `Impersonation` type describes it, and the [PHP docs](https://keyringauth.com/docs/0.x/impersonation#showing-a-banner) have a banner in React. `k.Impersonating(r)` says whether the browser is impersonating someone, as `Keyring::impersonating()`.

## The Time Limit

`Impersonation.Lifetime`, an hour by default. `Register` refuses one under a second while the feature is on. `Sessions.Absolute` caps it.

```go
cfg.Impersonation.Lifetime = 30 * time.Minute
```

It ends by itself `Lifetime` after it started, and the next request goes back, as in the PHP package. A page visit goes to `Impersonation.ReturnURL` with the `impersonation-ended` status, and a JSON request gets a `409` with the same status, message and `redirect`. Unused for `Sessions.Idle`, it ends sooner. The impersonator's session has usually idled out too, so the browser is signed out.

Set the fields of `cfg.Impersonation` one at a time. Assigning the whole struct leaves `Lifetime` at zero, which `Register` refuses.

## The Sessions List

The impersonated session shows in the user's sessions list with `"impersonated": true` and `"impersonator": { "name" }`, with no name, address or device of its own, as in the PHP package, and the user 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": "Admin Ada" }
}
```

`impersonator` is `null` once the impersonator's account is gone. To hide the session from the list, unless it's the one asking, set `Impersonation.ShowInSessions` to false:

```go
cfg.Impersonation.ShowInSessions = new(false)
```

`nil` is on. It still counts in "sign out everywhere else", which ends it.

## Security Log and Events

As in the PHP package: the start and end are logged on both accounts as `impersonation_started` and `impersonation_ended`, with `impersonator`, `user` and `role` (`impersonator` or `impersonated`), and the end's `reason` and `returned`. A refused start is logged as `impersonation_refused` on the impersonator's account, with `reason` and `user`, as a refusal `SecurityLog.Refusals` caps. Entries on the user's account leave off the request's address and browser, which are the impersonator's. The end reasons are `stopped`, `expired`, `revoked`, `impersonator_session_ended`, `lost` and `signed_out`. A start that was logged but couldn't hand the browser over is logged as ended with `failed`, and fires no event.

`keyring.ImpersonationStarted[U]` (`Impersonator`, `User`, `Handle`) and `keyring.ImpersonationEnded[U]` (`Impersonator`, `User`, `Reason`, `Returned`, `Handle`) fire as the PHP package's events. `Handle` is the impersonated session's, as the user's sessions list knows it. The impersonated session's record ends as `impersonation_ended`, which `RegisteredSessionEnded` gives. See [Events](https://keyringauth.com/docs/0.x/go/events#sessions-and-devices).

`Impersonation.ShowInActivity` is there for the PHP package's `show_in_activity`, but Keyring for Go has no activity feed yet, so nothing reads it.

## How It Works

As in the [PHP docs](https://keyringauth.com/docs/0.x/impersonation#how-it-works), with these differences:

- **One ending.** Only one request ends an impersonation, by a claim on its handle in the default cache store, where the PHP package uses `cache.limiter`'s.
- **Session IDs.** [`Sessions.OverlappingRequests`](https://keyringauth.com/docs/0.x/go/devices-and-sessions#requests-that-overlap-a-sign-in) keeps a request that finishes after a start or stop from saving the old session back, as in the PHP package. The check against a parked record above stands in where it can't.
- **Failed starts.** A start that can't be logged fails with the log's error, and the browser stays as it was. One whose session can't be saved has its record ended rather than left for the sweep.

## Migrating From Another Package

The PHP packages this section covers have no Go counterparts. Their concepts map as the [PHP docs](https://keyringauth.com/docs/0.x/impersonation#migrating-from-another-package) show, with `AllowImpersonationWhen`, `Impersonate`, `StopImpersonating`, `Impersonating` and `RefuseWhileImpersonating` in place of the facade methods and middleware.
