Account SecurityDevices & Sessions

Devices & Sessions

On this page

Introduction

Keyring tracks two things for each user:

  • Devices are the browsers a user has signed in from, recognised by a cookie. Devices feed your policy and risk signals, but they're never a factor. Turn them on with Features::devices().
  • Sessions are every signed-in session, kept in Keyring's own registry, so Keyring can list and revoke them whichever session driver Laravel uses (database, file, cookie or cache). Sessions are always on.

Use them to show users where they're signed in, let them sign out everywhere else, and have Keyring end sessions after a password change or on inactivity. With end_on_lapse, Keyring also ends a session when its assurance level lapses.

PHP
'features' => [    Features::devices(),],

Without devices, Keyring sets no device cookie and records no devices, and the device routes aren't registered. The NewDevice and InactiveAccount risk signals need devices. NewCountry and ImpossibleTravel need devices too, and a locator. Devices also let Keyring keep part of an account's failure allowance for browsers it has signed in from (limits.consecutive_elsewhere), so someone else's failed guesses can't lock the owner out of their own device.

Devices

With devices on, every sign-in looks for Keyring's device cookie. If it's missing or unknown, Keyring creates a device and sets a new cookie. The cookie is httpOnly and SameSite=Lax, and lasts 400 days (devices.cookie_lifetime). Only a SHA-256 hash of its token is stored. For the cookie's name, see Keyring's Cookies.

An account keeps its 50 most recently seen devices (devices.limit). When a sign-in from a new browser would go over that, the device seen longest ago is forgotten and signed out. A browser coming back on "remember me" never makes room this way. Once the account is at the limit, a browser the account hasn't used gets no device. Its session is on none, and Keyring dispatches UnrecordedDeviceSignedIn instead of NewDeviceSignedIn. Ending that session, or signing out everywhere, ends it.

A browser shared by several accounts has one cookie and one device per account. An account never takes a cookie value the browser sent, since it could belong to someone else. So the first sign-in on a shared browser gives it a new cookie, and the other accounts' devices move to it.

Trusted Devices

Trust lets a user skip the second factor on a browser they've chosen to trust. When devices.trust_for isn't null, the challenge page offers "don't ask again on this device" (canTrustDevice). Posting trust: true with the login marks the device trusted for trust_for (30 days by default), counted from when trust is granted.

Trust is only granted when that login reached AAL2, such as a password plus an authenticator app's code. If Features::emailVerification() is on, the email address must also be verified. An emailed code doesn't count as a second factor, so a password plus an emailed code earns no trust. Granting trust gives the browser a new cookie, so trust never rests on a cookie that was copied or planted before the login.

Trust does nothing on its own. Your policy has to use it:

PHP
Keyring::require(fn (User $user, Attempt $attempt) => $attempt->device()?->isTrusted()    ? Requirement::aal1()    : Requirement::aal2()->ifEnrolled());

Every device stops being trusted when:

  • the password is changed or reset,
  • an authenticator is removed, or a factor that allows only one per user is replaced (new recovery codes don't count),
  • an email change is applied or reverted,
  • a signed-in request places a risk lock, or a signed-in session meets a critical risk.

Risk detected at login doesn't touch the owner's sessions or trusted devices.

New Device Sign Ins

A sign-in from a new device dispatches Keyring\Events\NewDeviceSignedIn. Keyring also sends the new_device security email, unless you set new_device to null in Keyring::notifications(). keyring:install turns on the NewDevice risk signal only when devices are on.

Listen for Keyring\Events\UnrecordedDeviceSignedIn too. It fires when a browser comes back on "remember me" to an account at devices.limit. There's no device, so there's no "this wasn't me" link, and device is only a readable name for the browser.

PHP
use Illuminate\Support\Facades\Event;use Keyring\Events\NewDeviceSignedIn;use Keyring\Events\UnrecordedDeviceSignedIn; Event::listen(function (NewDeviceSignedIn $event) {    $event->user->notify(new NewSignIn($event->device->description(), $event->revokeUrl()));}); Event::listen(function (UnrecordedDeviceSignedIn $event) {    $event->user->notify(new NewSignIn($event->device ?? 'An unknown browser', null));});

$device->description() adds the location when it's known, as in "Chrome on macOS near Leeds".

$event->revokeUrl(), or $device->revokeUrl($days), returns a signed link to the device's report page. It's valid for 7 days by default (devices.report_link_for). The link is built from APP_URL, and its signature covers the path and query, so a forged Host header can't point it somewhere else.

Opening the link shows the device-report page, with the props device, url, expires and signature. It changes nothing, so mail scanners that follow links can't sign anyone out. Its button posts expires and signature in the body to the link's path. That POST revokes the device without the user signing in. The device's sessions end, it stops being trusted, and the user's "remember me" cookies stop working. The user lands on the login page with the device-reported status. The event is logged as device_reported, which shows as a "was this you?" alert at their next sign-in.

The POST must not carry the signature in its URL. Keyring refuses such a request with a 403, so the signature stays out of access logs and proxies.

Blade
<form method="POST" action="{{ $url }}">    @csrf    <input type="hidden" name="expires" value="{{ $expires }}">    <input type="hidden" name="signature" value="{{ $signature }}">    <button>Sign {{ $device }} out</button></form>

Locations

Keyring asks a locator for the rough location of each request. The default, Keyring\Devices\NullLocator, knows nothing, so locations stay empty and the location risk signals stay quiet.

To turn locations on, set devices.locator to a class that implements Keyring\Contracts\LocatesIps. Recipes has one for stevebauman/location:

PHP
use Illuminate\Http\Request;use Keyring\Contracts\LocatesIps; class IpLocator implements LocatesIps{    public function locate(Request $request): ?array    {        $record = app(IpDatabase::class)->lookup($request->ip());         return $record === null ? null : [            'country' => $record->countryCode,            'city' => $record->city,            'latitude' => $record->latitude,            'longitude' => $record->longitude,        ];    }}

The array can hold country, region, city, latitude and longitude. Impossible travel needs the coordinates. Keyring calls the locator at most once per request. Your own code can read the result with Keyring\Devices\Location::of($request).

If the locator throws, the location is treated as unknown for that request, the exception goes to report(), and the sign-in carries on.

Keyring\Devices\HeaderLocator reads location headers that a proxy or CDN adds. By default it reads Cloudflare's: CF-IPCountry, CF-Region, CF-IPCity, CF-IPLatitude and CF-IPLongitude. For another proxy, set devices.locator to HeaderLocator::class and bind it with your own map of location fields to header names:

PHP
use Keyring\Devices\HeaderLocator; $this->app->bind(HeaderLocator::class, fn () => new HeaderLocator([    'country' => 'X-Country-Code',    'city' => 'X-City',]));

Warning

Only use HeaderLocator when requests can't reach your app without passing through that proxy. Anyone can send those headers.

Device Names

Keyring's user agent parsing only knows common browsers and platforms. To use a real parser, pass a closure that takes the user agent string and returns a name, or null. Call it from a service provider's boot() method:

PHP
use Keyring\Facades\Keyring; Keyring::describeDevicesUsing(fn (string $userAgent) => app(UserAgentParser::class)->parse($userAgent)->summary());

Keyring stores the user agent trimmed to 500 characters. UserAgent::from($request) returns the same value.

Your Own Device Model

To add relationships or methods to devices, extend Keyring\Models\Device and tell Keyring to use your class:

PHP
use App\Models\Device; Keyring::useDeviceModel(Device::class);

$user->devices(), the risk signals, keyring:prune and the device routes all use your model. It has two query scopes: ownedBy and active, which leaves out revoked devices.

PHP
Keyring::deviceModel()::query()->ownedBy($user)->active()->get();

Listing and Revoking Devices

With devices on, GET /user/devices returns the user's devices that haven't been revoked, most recently seen first. A device is a browser. Its sessions count is the number of sessions on it.

JSON
{  "devices": [    {      "id": "01JC6...",      "name": "<browser> on <platform>",      "description": "<browser> on <platform> near Leeds",      "ip": "203.0.113.7",      "location": { "country": "GB", "city": "Leeds" },      "lastActiveAt": "2026-11-08T13:55:00+00:00",      "trusted": false,      "current": true,      "sessions": 1    }  ]}

DELETE /user/devices/{device} revokes one device. Its sessions end, it stops being trusted, and the user's "remember me" token changes. The answer is the device-revoked status. If that device is the current one, this session is signed out too, and the answer redirects to the login page. JSON clients get the redirect as redirect.

DELETE /user/sessions is always registered, so you can always offer "sign out everywhere else". With devices on, DELETE /user/devices does the same under another name. Each signs out every session except the current one, changes the "remember me" token, stops trusting every other device, cancels a pending email change, and gives the current session a new ID. The new ID signs out anyone holding a copy of its cookie. The answer is sessions-revoked.

From your own code, Sessions::signOutOthers() does the same. It returns how many sessions it ended and dispatches SessionsRevoked:

PHP
use Keyring\Sessions\Sessions; app(Sessions::class)->signOutOthers($request, $user); // Or step by step.app(Sessions::class)->signOutEverywhere($user, except: app(Sessions::class)->current($request)?->id); app(Sessions::class)->rotate($request);

rotate gives the session a new ID on every session driver and moves it to a new registry record. Only the request that rotated knows the new record, which is what signs out a copy of the old cookie. Keyring rotates after every step-up and when a sign-in method is added. A password change signs out the other sessions too, unless you tell it not to. A user can also choose to do the same when adding or removing a sign-in method. See Signing Out Other Sessions.

Note

The DELETE routes for devices and sessions are refused during an impersonation. They also need a verification in the last 15 minutes by default (changes_middleware). See Routes.

Listing and Ending Sessions

GET /user/sessions returns every session the user could still carry on, most recently active first. It reads the registry, so it includes sessions with no device, such as one your own Auth::login() started in a browser Keyring hadn't seen.

JSON
{  "sessions": [    {      "id": "9f2c41d0...",      "name": "<browser> on <platform>",      "ip": "203.0.113.7",      "device": "01JC6...",      "remembered": false,      "signedInAt": "2026-11-08T09:12:00+00:00",      "lastActiveAt": "2026-11-08T13:55:00+00:00",      "expiresAt": "2026-12-08T09:12:00+00:00",      "current": true,      "impersonated": false,      "impersonator": null    }  ]}
  • id is a handle, not the registry ID. The registry ID goes in the "remember me" cookie, so it never reaches a page. The handle is an HMAC-SHA256 of the ID of the record the session started on, keyed with APP_KEY. It can't be turned back into an ID, and it stays the same when the session moves to a new record.
  • device is the ID of the session's device, or null when there's no device or devices are off.
  • lastActiveAt is updated at most once a minute.
  • impersonated is true when someone else is signed in as the user, and impersonator says who, as {"name": "..."}, or null once they're deleted. Such a session has no name, ip or device, since those would be the impersonator's. It's left out when impersonation.show_in_sessions is off, unless it's the session asking. See Impersonation.

Changing APP_KEY changes every handle. A handle made under a key you've moved to APP_PREVIOUS_KEYS still works until you take that key out of the list.

DELETE /user/sessions/{session} ends the session with that handle. Its record is revoked, so the browser is signed out on its next request, and its "remember me" cookie brings nothing back. Other remembered browsers stay signed in. The answer is session-revoked, and SessionsRevoked is dispatched with a count of one.

A handle that isn't one of the user's own sessions gets a 404, and the attempt is logged as access_refused and dispatches AccessRefused. A value that isn't shaped like a handle doesn't match the route at all. That includes a registry ID.

Ending the current session is signing out. Keyring does everything POST /logout does, including changing the "remember me" token and dispatching LoggedOut. A JSON client gets a 204, so send the user to your login page when current was true. The token change also signs out the user's other remembered browsers. See Known Limitations.

From your own code:

PHP
use Keyring\Sessions\Sessions; $sessions = app(Sessions::class); $sessions->list($request, $user);            // what the route returns$sessions->active($user);                    // the same sessions as RegisteredSession objects $session = $sessions->find($user, $handle);  // null unless it's one of the user's own$sessions->revoke($user, $session); $current = $sessions->current($request);     // null outside a Keyring session$handle = $current ? $sessions->handle($current) : null;

Store the handle, never the registry ID. A session keeps its handle when it moves, so you only need to store it once.

Is It Still Signed In?

Other code sometimes knows a session by its handle and needs to know whether it still counts. A single sign-on provider that signed a client in on the session is one example. Ask stillSignedIn:

PHP
use Keyring\Sessions\Sessions; if (! app(Sessions::class)->stillSignedIn($user, $handle)) {    // The user has signed out of that session, or it has ended.}

It returns true only when your app still lets the user sign in (Keyring::allowSignInWhen) and the handle is one of the user's own sessions that can still be carried on. Revoked, expired and idled-out sessions give false, and so does any value that isn't one of the user's handles. It also gives false for a user model that isn't Eloquent. For a user who hasn't verified their address, when registration hides who has an account (the default), it gives false too, unless the request follows that user's verification link. A token refresh made from anywhere else would otherwise log such users out.

Asking doesn't count as activity, so it never keeps a session from idling out, and it doesn't sign anyone out. The session's next request does that.

Some checks only run on the browser's own requests, so stillSignedIn can't see them: sessions.end_on_lapse, risk locks and the per-request risk signals. It also says only that the user is signed in, not how strongly. A session whose Laravel session has expired still answers true until it idles out. With sessions.idle set to null, that's at absolute. Keep idle no longer than session.lifetime if the answer shouldn't outlast Laravel's session.

Hearing About Ended Sessions

Listen for Keyring\Events\RegisteredSessionEnded to react when a session ends. It fires for every registered session that ends, whoever ended it: a sign-out, signing out everywhere, ending a session or device, the limits, a deleted user, a risk response, a password or email change, or the session middleware finding a session idle, expired, reused or refused. See Events for the properties and reasons.

PHP
use Illuminate\Support\Facades\Event;use Keyring\Events\RegisteredSessionEnded; Event::listen(function (RegisteredSessionEnded $event) {    // Every handle the session goes by, so one stored before a key rotation matches.    ClientSession::whereIn('keyring_handle', $event->handles)->each->logOut();});

ClientSession stands for whatever your app stores against a handle. Match on handles, not only handle, which is the handle under the current key. A stored handle stops matching when APP_KEY is rotated without the old key in APP_PREVIOUS_KEYS, or when a driver of your own loses origin. stillSignedIn fails safe in that case, so code that keeps someone signed in elsewhere should ask it now and then.

With keyring:sign-out --all or the registry's revokeEveryone(), Keyring can't list each session, so it dispatches one Keyring\Events\EveryoneSignedOut instead. Its at is a cut-off: every session that signed in up to at has ended, and later sign-ins are still good. End only what your app holds for sessions that signed in up to at, never "everything, now". On the database driver, the sweep sends it again if the first one was lost, up to a day late.

Each revoked record is announced once, so two requests ending the same session at once announce it once between them. Nothing is announced when a session moves to a new record or when keyring:prune deletes records.

The timing depends on the driver. On database, the event goes out after the transaction that revoked the session commits, and not at all if that transaction rolls back. On cache, it goes out as soon as the session is revoked, and a cache that's cleared or evicts records ends sessions with no event. A driver of your own is announced as soon as it's revoked, unless it extends DatabaseSessionRegistry. Two cases need the sweep to be announced: a session that times out with no request to end it, and a revocation whose event was lost after its commit. The cache driver can't be swept.

The event can come more than once, so make your listener idempotent. Logging a client out twice should do nothing the second time.

Keyring dispatches the event in the request or command that ended the session. Queue your listener (ShouldQueue) if it's slow, since signing out everywhere can end many sessions at once. Don't wait for a commit: Keyring already dispatches after the right one. A ShouldQueueAfterCommit listener, or a queue with after_commit on, waits for whichever transaction opened last, and drops the job if that one rolls back.

A listener that throws doesn't stop the sign-out, and the exception is reported. But Laravel stops at the first listener that throws or returns false, so a failing listener can stop later listeners hearing the event. Queue your listeners, and don't return false from them.

Sweeping Ended Sessions

The sweep is off by default. Without it, a session that times out with no request to end it is never announced, and neither are lost events. To turn it on, set sweep_every. Keyring then adds php artisan keyring:sweep to Laravel's scheduler, ahead of keyring:prune:

PHP
'sessions' => [    'sweep_every' => '5m',    'sweep_limit' => 1000,],

sweep_every takes minutes or hours, such as '1m', '5m' or '1h'. Use a step that divides an hour or a day. Over an hour it's rounded down to whole hours, so '90m' runs hourly. Anything longer than 12 hours runs every 12 hours. Zero, or anything that isn't a duration, turns the sweep off with a warning in your log, and keyring:sweep prints the problem.

Note

The scheduled sweep needs the scheduler running and a cache store that every server shares and that supports locks, such as Redis, Memcached or the database store. It runs on one server at a time. Without a lock store, each server may run its own sweep, which is safe but wasteful.

On the database driver, the sweep does two things. It announces again any session whose event never went out, waiting five minutes after the revocation so an event still on its way isn't doubled. It also ends each session that timed out with no request to end it, announcing it as idle or expired. It ends only what the middleware would end on the next request: past absolute, or unused for longer than idle (remember_idle for a remembered one). It never ends sessions for a level's limits or for end_on_lapse, which depend on what the browser proved. Nor does it end sessions of accounts your app no longer lets sign in. For those, call signOutEverywhere as For Administrators shows. The limits come from the config of the process running the sweep.

sweep_limit (default 1000, at most 10000) caps how many sessions one run announces and how many it ends. The first run after an upgrade therefore doesn't announce thousands at once. The sweep gives up on a revocation a day old. A failing listener is retried after five minutes, then ten, doubling until the day is out.

The sweep locks the rows it's about to end and decides again from them, so a session a request just used is kept.

The sweep needs four columns that a migration adds to keyring_sessions: announced_at, end_reason, announce_attempts and announce_after. Until the migration runs, Keyring logs a warning once a day and keyring:sweep refuses to run. Sessions revoked before the migration count as announced.

Remember Me

When a user ticks "remember me", Laravel sets a token cookie that signs the browser back in. On its own, that token would work for as long as the browser sent it, whatever happened to the session. So Keyring adds a cookie that names the session's registry record. When Laravel's cookie signs a browser back in, Keyring checks that record:

  • If the record belongs to the user, hasn't been revoked, is inside its absolute limit, and was last used within remember_idle (14 days by default), the session carries on. It moves to a new record and gets a new cookie. The new record keeps the same start and expiry, so coming back never restarts the absolute limit. Its device, IP address and browser come from the request that came back, and it starts with no assurance level.
  • Otherwise the request is signed out and both cookies are cleared. This happens when the cookie names no record, an expired one, or a revoked, timed-out or someone else's record.

A remembered sign-in is refused while the account is risk locked. A session that carries on dispatches Keyring\Events\SessionResumed, logged as session_resumed, so the security log shows every time a browser came back.

Your own Auth::login($user, remember: true) gets the Keyring cookie too, on the response that signs in, as long as that route has the middleware. See Timeouts for how long a remembered browser can stay away.

Each Keyring cookie works once. Coming back replaces the record it names and gives the browser a new cookie. So if a copy of the cookies is used alongside the original, only the first to come back gets the session. Keyring can't tell which browser is the owner's, so the session ends for both:

  • the request is signed out with reused as the reason,
  • the record the session has moved to is revoked, which signs the other browser out on its next request,
  • Keyring\Events\RememberMeReused is dispatched with the user and the ended session, logged as remember_me_reused. It's one of the default "was this you?" alerts.

The user's remember token is left alone, so their other remembered browsers stay signed in. To do more, such as signing out everywhere, listen for the event:

PHP
use Illuminate\Support\Facades\Event;use Keyring\Events\RememberMeReused;use Keyring\Sessions\Sessions; Event::listen(function (RememberMeReused $event) {    app(Sessions::class)->signOutEverywhere($event->user);});

A browser that comes back usually sends several requests at once, all carrying the cookie the first one uses up. So for sessions.remember_grace (10 seconds by default), a request with a cookie replaced a moment ago joins the session the first request resumed, if it comes from the same user agent. A cookie reused from a different browser counts as used twice. Set the grace period to 0 only if a browser's requests never overlap.

Timeouts

PHP
'sessions' => [    'idle' => '2h',    'remember_idle' => '14d',    'absolute' => '30d',    'levels' => [        'aal2' => ['idle' => '1h', 'absolute' => '24h'],        'aal3' => ['idle' => '15m', 'absolute' => '12h'],    ],    'end_on_lapse' => false,],
  • idle ends a session after this much inactivity. It defaults to two hours, the lifetime of Laravel's session in a new app, and Keyring counts it on the registry record, whatever your session driver. An idled-out session can't be picked up again. null leaves inactivity to Laravel's session lifetime.

Inactivity and "Remember Me"

Ticking "remember me" asks to stay signed in between visits, so idle can't apply to that browser. Otherwise the checkbox would do nothing. Instead:

  • A remembered session isn't ended by idle. It's ended by remember_idle after 14 days without a request, or by absolute 30 days after sign-in. Coming back never restarts absolute.
  • Once a session has been unused for idle, it keeps nothing it proved. A browser that comes back on its cookies starts with no level, so routes behind keyring:aal2 or keyring.fresh ask the user to verify again.
  • A remembered browser left unattended still opens anything behind auth alone. Put anything that shouldn't be reachable that way behind a level or a fresh verification, or don't offer "remember me". To avoid offering it, leave the remember field off your login form, or set remember_idle equal to idle. Keep remember_idle no shorter than idle, or ticking the box signs people out sooner. NIST SP 800-63B-4 (Sec. 5.1) doesn't accept a cookie in place of authentication, so an app following it should leave the checkbox out. See Known Limitations.

A level lapses on its own clock, without ending the session. It lapses after its idle with no request, or after its absolute limit counted from the verifications that reached it. The user stays signed in at whatever level is left. Once inactivity has lapsed a level, every factor for that level is asked for again, and nothing verified before the lapse counts toward it.

Ending a Session With Its Level

NIST SP 800-63B-4 (Sec. 5.2) says a session ends when its inactivity or overall timeout passes. It also allows a session to be treated as a lower level than it was authenticated at (Sec. 5.1). Keyring does the latter by default. A session that signed in with two factors stops being AAL2 after an hour idle or 24 hours, and carries on as the AAL1 session its password alone would have started, under idle and absolute. Nothing behind keyring:aal2 or keyring.fresh is reachable in the meantime. Ending those sessions outright would sign out people who set up a second factor.

If the whole app should be AAL2, or you want NIST's wording exactly, turn the lapse into the end of the session:

PHP
'sessions' => [    'end_on_lapse' => true,],
  • A session ends on the first request after the level it signed in at runs out. That's after the level's idle with no request, or after its absolute limit counted from when the factors were proved. The reason on SessionEnded is idle or expired.
  • Proving every factor for that level again before then starts both limits over.
  • A level reached later by a step-up still lapses on its own, and takes nothing with it.
  • A risk response that asks a signed-in session to step up ends it too, with the reason risk.
  • An impersonator whose session signed in above AAL1 is signed out when the impersonation ends, not returned at AAL1. See Impersonation.
  • "Remember me" brings nothing back, because its cookie proves nothing. Leave the checkbox off your login page.

The timeouts leave AAL1 sessions as they are, since idle and absolute already end those. Recipes has the full setup for an app where every page needs AAL2.

How Many Sessions

An account can be signed in 100 times at once (sessions.max). A sign-in beyond that still succeeds. Keyring ends the account's session that has gone unused longest. The registry event's reason is session_limit, and the browser is signed out on its next request. A session that has already idled out goes first. A session someone is impersonating the user in doesn't count here, and isn't ended to make room.

PHP
'sessions' => [    'max' => 100,],

The default of 100 is twice the default devices.limit of 50, which leaves room for each device to have two sessions: the one in use and one left behind. The two settings are separate, so you can change one without the other. Set max to 1 to allow a single session, so each sign-in ends the last. Set it to null for no limit. Keyring never refuses a sign-in because of the limit, since refusing would let whoever holds an account's sessions keep its owner out.

Only sessions count. Revoked, expired and moved-on records don't. Sign-ins for one account are counted one at a time, so two can't both slip under the limit.

Pages That Also Serve Guests

Some pages work for guests too, like a public page that shows more when you're signed in, or an OIDC authorize endpoint that has to answer prompt=none itself. Sending those to the login page when a session ends is wrong. List their route names in sessions.continue_as_guest. The list takes names the way Request::routeIs() does, wildcards included:

PHP
'sessions' => [    // ...    'continue_as_guest' => ['welcome', 'oauth.authorize', 'docs.*'],],

When a session ends on a GET visit to one of those routes, the browser is signed out, SessionEnded is dispatched as usual, and the browser is redirected back to the URL it asked for, so it requests the page again as a guest. The query string is kept. The signed-out status is flashed, so a page that shows statuses can say why. No intended URL is saved, so the next sign-in doesn't return to this request. The redirect comes ahead of your own SignedOutResponse, so binding one doesn't change this.

JSON requests still get the 401. HEAD, POST and other methods are signed out as before. An Inertia visit gets a 409 with an X-Inertia-Location header rather than a redirect, which makes Inertia load the page in full.

This applies to every reason a session ends, including reused, risk, and an impersonation ending with nothing to go back to (impersonator_session_ended or lost, which dispatch ImpersonationEnded instead).

Only list pages that guests can see. Routes behind auth send guests to log in anyway. Routes without a name can't be listed, and a broad pattern like * also matches Keyring's own pages. If any entry isn't a non-empty string, Keyring ignores the whole list.

For Administrators

Whoever runs your app can end sessions without waiting for them to time out.

Terminal
php artisan keyring:sign-out 42php artisan keyring:sign-out taylor@example.comphp artisan keyring:sign-out --all

The user is named by ID or by username. The command reports who it signed out and how many sessions ended. It does what Sessions::signOutEverywhere($user) does: every session is revoked, the "remember me" token changes, no device stays trusted, and a pending email change is cancelled. It dispatches SessionsRevoked. If the name is one user's ID and another user's username, nobody is signed out. The command names both, and you run it again with --id for the ID.

--all ends every session that signed in up to that moment, on whichever record it's on, and asks first unless you pass --force. Each browser is signed out on its next request, and "remember me" brings none back. Trusted devices, "remember me" tokens and pending email changes are left alone. It dispatches one EveryoneSignedOut.

From your own code, such as an admin screen:

PHP
use Keyring\Contracts\SessionRegistry;use Keyring\Facades\Keyring;use Keyring\Sessions\Sessions; app(Sessions::class)->signOutEverywhere($user);   // one user, returns how many sessions ended app(SessionRegistry::class)->revokeEveryone();    // everyone Keyring::unlock($user);                           // let a locked-out user try again

Keyring::unlock lifts a risk lock and the sign-in lockouts on the account. To keep someone out for good, use Keyring::allowSignInWhen and call signOutEverywhere when you set your flag. The gate alone only ends an account's sessions when the next one makes a request.

As with any sign-out that isn't the browser's own, these take effect on a session's next request, where the session middleware runs.

Pruning

php artisan keyring:prune deletes what Keyring no longer needs:

  • devices revoked more than 30 days ago, or not seen for a year (devices.keep_revoked_for and devices.keep_unseen_for),
  • email changes that ended more than 30 days ago (email_changes.keep_ended_for), since they hold both addresses,
  • security log entries older than security_log.keep_for,
  • when an account last removed or replaced an established sign-in method, once that no longer freezes anything (authenticator_changes.established_after),
  • password holds lifted more than a year ago,
  • registered sessions that have expired or been revoked, through the registry's prune method. A record that "remember me" moved a session on from is kept until it expires, so its cookie is still recognised as used. Once the sweep's migration has run, a session waits until a sweep has announced it, or for a day.

Keyring schedules the prune itself, daily at 03:00, so it runs wherever your schedule:run does. php artisan schedule:list shows it. Change the time with prune_at, or set it to null to schedule it yourself:

PHP
// config/keyring.php'prune_at' => '01:30',
PHP
// routes/console.phpuse Illuminate\Support\Facades\Schedule; Schedule::command('keyring:prune')->daily()->onOneServer();

Either way, your server has to run Laravel's scheduler (* * * * * php artisan schedule:run). Pruning also covers your own device model, because Keyring runs Laravel's model:prune for its own models. Laravel's plain model:prune only looks in app/Models.

Keyring's Cookies

Keyring sets cookies of its own. The device cookie identifies the browser. The "remember me" cookie ties a remembered browser to its session. With devices off, a finished sign-in gives the browser a third, the known-browser cookie: the account and when, encrypted with your app's key, which only decides which count of codes a later sign-in's code goes in. Their names depend on how your app is served:

Your App Device Cookie "Remember Me" Cookie Known-Browser Cookie
Served over HTTPS __Host-known_device __Host-remembered_session __Host-known_browser
Served over HTTPS, with session.domain set or session.path other than / __Secure-known_device __Secure-remembered_session __Secure-known_browser
Served over plain HTTP, as on http://localhost known_device remembered_session known_browser

The names say what the cookies are for, not what sets them. OWASP's Session Management Cheat Sheet recommends that, since a name that reveals the software also tells an attacker what to look for. Laravel's session cookie is yours to name (SESSION_COOKIE). See Secure Cookies.

Keyring treats your app as served over HTTPS when APP_URL starts with https://, or when session.secure is true, not by the request. Behind a proxy your app doesn't trust, every request looks like plain HTTP.

Over HTTPS they're always Secure. Keyring uses the __Host- prefix wherever it can, since no other subdomain can set or replace that cookie. A cookie shared with subdomains can't have that prefix, so it gets __Secure-.

To use names of your own, set devices.cookie or sessions.remember_cookie. Keyring uses the name exactly as you set it, and still makes it Secure over HTTPS. Adding a prefix is up to you.

A browser given the plain cookies before you moved to HTTPS keeps its device and remembered session. Keyring reads the plain cookie until the browser gets the new name, then deletes the plain one. A plain cookie is only used to find a device the account already has, never to create one, since anything on your domain could have set it.

The Session Middleware

Keyring\Http\Middleware\AuthenticateSession checks each signed-in request. Keyring adds it to the web group, followed by keyring.password, which does nothing until a user is held for a new password. If you set sessions.middleware to false, add both yourself, using the keyring.session alias and then keyring.password. See Requiring a Password Change. Give keyring.session to Keyring's own routes too, POST /logout above all.

The middleware only runs on routes it's attached to, and it needs Laravel's session to have started. A route that uses auth without StartSession lets a "remember me" cookie through with none of the checks. For signed-in sessions on other groups, add keyring.session there. The usual case is Sanctum's stateful api routes for a single-page app:

PHP
// bootstrap/app.php->withMiddleware(function (Middleware $middleware) {    $middleware->statefulApi();    $middleware->appendToGroup('api', 'keyring.session');})

The conformance suite fails for any route that uses auth on Keyring's guard without keyring.session, and names the route.

On each signed-in request, the middleware signs the user out if the record was revoked, has expired, belongs to someone else, has been idle too long, or was carried on by "remember me" somewhere else. It registers sessions that started some other way, such as your own Auth::login(). It carries a remembered session on when its cookie signs the browser back in, runs the cheap risk signals, and updates the last activity time at most once a minute. A session whose record has gone missing is signed out, not registered again, so clearing records can't restart its window.

A sign-out your app does itself ends the record too. Keyring listens for the guard's Logout and CurrentDeviceLogout events, so Auth::logout() and Auth::logoutCurrentDevice() revoke the record and forget its "remember me" cookie on any route. The record also ends after $request->session()->invalidate() followed by Auth::logout(), since the middleware notes the record before your code runs.

A signed-out request goes to the login page with the signed-out status, and comes back to where it was going after signing in. JSON clients get a 401:

JSON
{ "status": "signed-out", "message": "...", "page": "login", "redirect": "..." }

Either way the response sends Clear-Site-Data, and Keyring\Events\SessionEnded is dispatched with the reason and logged as session_ended.

Your Own StartSession

Keyring replaces Laravel's StartSession with its own, which changes how requests that overlap a sign-in are saved (see Requests That Overlap a Sign In). If your app binds its own subclass of StartSession, Keyring leaves it alone and logs a warning that requests to it can undo a sign-in. To keep your changes alongside Keyring's, extend Keyring's class and bind that instead:

PHP
use Illuminate\Contracts\Cache\Factory as CacheFactory;use Illuminate\Session\Middleware\StartSession;use Illuminate\Session\SessionManager; // App\Http\Middleware\StartSession extends Keyring\Http\Middleware\StartSession // AppServiceProvider::register()$this->app->singleton(StartSession::class, fn ($app) => new \App\Http\Middleware\StartSession(    $app->make(SessionManager::class),    fn () => $app->make(CacheFactory::class),));

Keyring's class overrides handle(), startSession() and saveSession(), and calls Laravel's in each. If your override changes one of them too, call the parent. If your class has to extend another package's StartSession subclass, use the Keyring\Concerns\SkipsReplacedSessions trait in it instead. Keyring doesn't warn about a class that uses the trait, as long as it doesn't declare the trait's methods itself. Bind with singleton() or bind(). An instance given to the container with app()->instance() is never built, so Keyring can't replace it.

Writing a Driver

To write your own session registry, implement Keyring\Contracts\SessionRegistry and register it with the registry manager in a service provider's register() method:

PHP
use Keyring\Sessions\SessionRegistryManager; $this->app->afterResolving(SessionRegistryManager::class, function (SessionRegistryManager $manager) {    $manager->extend('custom', fn ($app) => new MySessionRegistry($app->make('db')->connection('sessions')));});

Then set sessions.driver to custom. Keyring wraps every driver in Keyring\Sessions\AnnouncingSessionRegistry, which dispatches a RegisteredSessionEnded for each record that revoke, revokeAll and revokeDevice return. A record your driver revokes and leaves out is never announced, and one it returns twice is announced twice. A custom driver is announced as soon as it's revoked, unless it extends DatabaseSessionRegistry. Only a driver that extends DatabaseSessionRegistry can be swept, so keyring:sweep does nothing for any other.

If your driver revokes a user's records one by one and can fail part way, finish what it can, then throw Keyring\Exceptions\PartialRevocation holding the records it revoked and the failure. Keyring announces those and rethrows.

Mark parameters that hold a registry ID, or a RegisteredSession, with #[\SensitiveParameter], as the contract does. app(SessionRegistry::class) gives the wrapper, and its inner() method gives your driver. A SessionRegistry you bind in the container yourself isn't wrapped, so nothing it ends is announced. The conformance suite checks for this.

Keyring calls replace, revokeAll and revokeDevice, and stores a new session, while it holds the user's row. That happens when sessions.max isn't null and the user is an Eloquent model, so for one user those calls never overlap. The contract's methods are:

Method Does
save($session) Stores a new RegisteredSession, every field included (origin and the impersonation fields too). It must never clear a revocation, or what a record was replaced by, made in the meantime. $session->toArray() gives the fields, and RegisteredSession::fromArray() reads them back.
find($id) Returns the session, or null, with every field it was saved with. A driver that loses origin gives a session a new handle each time it moves.
forUser($user) Returns the user's sessions that haven't expired, been revoked or been replaced, most recent first. Match on userType (RegisteredSession::typeOf($user)) as well as userId, so two user models with the same IDs don't share sessions.
update($id, $changes) Changes only the named fields, such as ['lastActivityAt' => $now]. RegisteredSession::columns($changes) turns them into column names.
revoke($id) Revokes one session and returns the record with revokedAt set, or null if there was nothing to revoke. Of two calls for the same record at once, only one may return it.
replace($id, $successor, $revoke = false) Moves a session to a new record, setting replacedBy and replacedAt on the old one, and revokes the old one when $revoke is true. It acts only on a record that's neither revoked nor replaced, and stores $successor only when it returns true. Of two calls at once, exactly one may return true, since "remember me" being single use depends on it.
revokeAll($user, $except = null) Revokes every session of the user but one, and returns a Collection of the records it revoked. Every record it revokes must be in that list. From your own code, call Sessions::signOutEverywhere, which also changes the remember token and trusted devices.
revokeDevice($user, $deviceId) Revokes the user's sessions on one device, and returns the records it revoked.
revokeEveryone() Revokes every user's sessions that signed in up to now, for keyring:sign-out --all. A session moving to a new record during this must end up revoked there too.
prune() Deletes sessions that have expired or been revoked, and returns how many. A replaced record stays until it expires, so a used "remember me" cookie can be told apart from one never issued.

Routes

Method URI Name Middleware Does
GET /user/sessions keyring.sessions.index auth:{guard} Lists the user's sessions as JSON.
DELETE /user/sessions/{session} keyring.sessions.destroy auth:{guard}, changes_middleware Ends one session by its handle.
DELETE /user/sessions keyring.sessions.destroy-others auth:{guard}, changes_middleware, keyring-session-changes limiter, session lock Signs out every other session.
GET /user/devices keyring.devices.index auth:{guard} Lists the user's devices as JSON. Devices on.
DELETE /user/devices/{device} keyring.devices.destroy auth:{guard}, changes_middleware Signs one device out. Devices on.
DELETE /user/devices keyring.devices.destroy-others auth:{guard}, changes_middleware, keyring-session-changes limiter, session lock Signs out every other session. Devices on.
GET /devices/{device}/report keyring.devices.report signed link, keyring-pages limiter Shows the "this wasn't me" page. Devices on.
POST /devices/{device}/report keyring.devices.report.store signed body, keyring limiter Signs the device out. Devices on.

The keyring.not-impersonating middleware is hard-coded on this route group, so these DELETE routes are refused during an impersonation even if you change changes_middleware. changes_middleware defaults to keyring.fresh:15m, a verification in the last 15 minutes. The three session routes are always registered. Listing needs only a signed-in user.

Events

The events are in Keyring\Events:

Event Properties
NewDeviceSignedIn user, device, and revokeUrl($days = null)
UnrecordedDeviceSignedIn user, handle (the session's), device (a readable name for the browser, or null). A browser came back on "remember me" to an account at devices.limit, so no device was recorded.
DeviceRevoked user, device, reported (whether it came from the "this wasn't me" link)
SessionsRevoked user, count. Fired after signing out everywhere else, ending one session, keyring:sign-out for one user, or the first request refused for an account your app keeps out.
SessionEnded user, reason (revoked, expired, idle, other_user, reused, risk or not_allowed)
RegisteredSessionEnded handle, handles, userId, userType, guard, deviceId, endedAt, reason. One for every registered session that ends. See Hearing About Ended Sessions.
EveryoneSignedOut at. Every user's sessions ended at once.
RememberMeReused user, session (the RegisteredSession that was ended), handle
ImpersonationStarted, ImpersonationEnded handle (the impersonated session's), among others. See Impersonation.
SessionContested user, session (the RegisteredSession that was ended), handle. See A Contested Session.
SessionResumed user, session (the RegisteredSession a remembered browser carries on as), handle
AccessRefused user, resource (device, session, authenticator or email_verification), id. Fired when a request for something that isn't the user's is answered with a 404, or when a verification link is made for another account.
LinkRefused link (the route's name), reason (signature or expired). A signed link, such as a "this wasn't me" link, that was refused.

handle is the session's handle. A listener in the request also sees the registry ID, but that's the "remember me" cookie's value, so a queued listener gets the record with a blank id and only the handle to go by.

How It Works

The Session Registry

Every signed-in session gets a record in Keyring's registry, with its own random ID. The record holds the user, device, assurance level, IP address, user agent, whether "remember me" was ticked, and timestamps. Laravel's session ID is never stored. The registry ID lives inside the session.

A session can move to a new record: when "remember me" carries it on, when a risk response asks it to verify again, and on every rotation (step-ups, password and email changes, "sign out other sessions", new sign-in methods). The old record then names its successor (replacedBy, replacedAt) and stops counting as a session. Each record also names the record the session started on (origin), which the handle is built from, so the handle stays the same.

Keyring checks the registry on every request, so a revoked session is signed out on its next request whichever driver you use.

PHP
'sessions' => [    'driver' => env('KEYRING_SESSION_DRIVER', 'database'),    'connection' => null,    'table' => 'keyring_sessions',    'store' => null,    // ...],
  • database (the default) uses the keyring_sessions table on connection. Its origin column comes from a migration of its own. Without it, a session can still sign in, but every move to a new record throws Keyring\Exceptions\MissingMigration and signs that browser out. If you installed Keyring before that migration, see the upgrade guide.
  • cache uses the cache store named in store, with no table. Use a persistent store, and one with locks. Without locks, a sign-out that lands in the middle of a "remember me" move can end the session with no event. If the cache is cleared, every session is gone and everyone signs in again.

Requests That Overlap a Sign In

A browser can send requests together. The login page asks for its passkey options as it loads, and someone quick can submit the password form before they come back. Signing in gives the session a new ID and destroys the old one. But Laravel saves the session at the end of every request, so a request sent with the old ID that finishes after the sign-in would save the old session again.

Keyring's Keyring\Http\Middleware\StartSession is Laravel's, with one change: a request doesn't save a session that another request replaced after it was sent, and doesn't send that session's cookies. It applies wherever Laravel's StartSession is resolved from the container, including the web group, Keyring's routes and Sanctum's stateful API. A session ID that your own code changes, through regenerate(), or a Fortify or Breeze sign-in, is remembered too, as that request ends.

Keyring remembers each session ID it replaces, and when, for five minutes (ReplacedSessions::REMEMBER_FOR). That covers every sign-in, step-up, sign-out, password or email change, and identity provider callback. A request sent with a replaced ID doesn't save the session if it started while the replacing request was still running, or within 10 seconds of that request's answer leaving (ReplacedSessions::SENT_WITHIN). Its answer doesn't send the session cookie, the XSRF-TOKEN cookie or the "remember me" cookies, so the browser keeps the new ID.

The IDs are kept hashed in the rate limiter's cache store (cache.limiter), so every server has to share that store, as it already must for rate limits. Use a store that never evicts a key before it expires. An evicted ID is forgotten, and requests sent with it are saved as Laravel would save them.

Warning

An array store is kept by each process alone. Outside your tests, Keyring warns when cache.limiter is one, or when it's null and your default cache store is one. The warning is logged once a day where the store is shared, and otherwise once per process, which under PHP-FPM is once per request.

Your frontend should expect what a browser holding a replaced ID sees. For the first 10 seconds after the replacing request answers, its requests get answers, but nothing they put in the session is kept unless they sign in.

If the replacing request died before answering, that lasts until a minute after the ID was replaced. In that minute the browser can't sign in with a password: form posts get a 419, and a passkey sign-in fails with a 422. After that, and for as long as Keyring remembers the ID, a request with the old ID gets a fresh, empty session under a new ID, with a new CSRF token. Nothing the old session held comes back.

Two things aren't covered. A request that reads the session after your code destroys it, but before that request ends, isn't stopped, since the ID isn't remembered yet. And an ID that doesn't change, such as a sign-out that calls Auth::logout() without invalidate(), can't be told apart from a slow request that saves an older session. Laravel's docs already ask for invalidate() and regenerate() there.

On Laravel's cookie session driver the session lives in the browser, so a browser can send back an older copy of it. Known Limitations covers what that allows.

To turn all of this off, set sessions.overlapping_requests to false. Keyring then remembers nothing, and an overlapping sign-in, step-up or sign-out can undo, as in any Laravel app:

PHP
// config/keyring.php'sessions' => [    'overlapping_requests' => false,],

A Contested Session

When a step-up, password change, "sign out other sessions", applied email change, new sign-in method or your own call to Sessions::rotate() finds that another request holding the same session has already moved the record on, Keyring can't tell which browser is the owner's. So the session ends for both:

  • the record the session has moved to is revoked with contested as the reason, and both browsers are signed out on their next request (revoked),
  • Keyring\Events\SessionContested is dispatched with the user and the ended session, logged as session_contested. It's one of the default "was this you?" alerts.

The other request may come from someone with a stolen cookie, but it isn't always someone else. Three harmless causes produce the same result: a form sent twice to a route that calls Sessions::rotate() without the session lock, a request that held the lock longer than its 10 seconds, and a rotation sent alongside a risk step-up that Keyring made. So word any alert as a question, and mention that submitting a form twice can cause it. Nothing is announced when the session had already ended some other way, such as a sign-out everywhere that landed first.

The session lock goes by session ID. The routes that sign other sessions out and give the session a new ID take it, so two of them sent with one ID run one after the other. They are PUT /user/password, DELETE /user/sessions, DELETE /user/devices, POST /email-changes/{change}/confirm, the step-up verify route, and the routes that add and remove sign-in methods. This only works when every server shares the lock store.