Limit How Many Devices a User Can Log In From
On this page
FusionAuth has no built-in limit on concurrent sessions. You can build one with refresh tokens, which FusionAuth issues once per login on each browser or device. Count a user's refresh tokens for an Application, and act when the count reaches your limit. A user who logs in from Chrome and Firefox on one computer has two sessions.
Choose what happens when a user goes over the limit:
| Outcome | How | Tradeoff |
|---|---|---|
| Block the new login | A user.login.success webhook returns an error. |
Simple. The user has to find and log out of another device, and the error message applies to every failed webhook. |
| Let the user pick a session to end | Middleware in your application checks the count after login and shows a list of sessions. | More code. The user stays in control, and each request makes an extra API call. |
Both approaches require centralized sessions. Each login must create a refresh token, and each logout must revoke the refresh token. Otherwise, logged out devices still count toward the limit.
Prerequisites#
- An Application with Generate refresh tokens turned on and the
Refresh Tokengrant enabled, on the OAuth tab. - A login request that includes the
offline_accessscope. - A logout route that revokes the session's refresh token. For an example, see Log Out of One Device.
- An API key with
GETandDELETEpermissions on/api/jwt/refresh.
Count a User's Sessions#
Call the Retrieve Refresh Tokens API with the user's Id. The response includes refresh tokens for every Application, plus the user's SSO sessionThe session FusionAuth keeps in the browser after a user logs in through the hosted login pages. While the SSO session lasts, FusionAuth logs the user in to other Applications in the Tenant without asking for credentials., which has no applicationId. Keep only the tokens for your Application:
const { refreshTokens = [] } = (await apiClient.retrieveRefreshTokens(event.user.id)).response;
// the SSO session and other applications' tokens don't count
const activeSessionCount = refreshTokens.filter((token) => token.applicationId === clientId).length;Block the New Login#
FusionAuth sends the user.login.success event after the user enters valid credentials and before FusionAuth completes the login. When the webhook transaction requires the webhook to succeed, a non-2xx response stops the login.
-
Navigate to Tenants -> Your Tenant -> Webhooks . Enable
user.login.success, and set the transaction level for the event toAny single webhook must succeed. -
Navigate to Settings -> Webhooks and add a webhook. Set URL to your endpoint, such as
https://app.example.com/user-login-success, and selectuser.login.success. In production, secure the webhook. For more information, see Secure Webhooks. -
In the endpoint, ignore events for other Applications, count the sessions, and return
403when the user is at the limit:Block a login over the limit app.post('/user-login-success', async (req, res) => { const event = req.body.event as UserLoginSuccessEvent; if (event.applicationId !== clientId || !event.user?.id) { res.sendStatus(200); return; } const { refreshTokens = [] } = (await apiClient.retrieveRefreshTokens(event.user.id)).response; // the SSO session and other applications' tokens don't count const activeSessionCount = refreshTokens.filter((token) => token.applicationId === clientId).length; // a non-2xx response stops the login when the webhook transaction requires success if (activeSessionCount >= maxDeviceCount) { console.log(`blocked login for user ${event.user.id}: ${activeSessionCount} of ${maxDeviceCount} sessions in use`); res.sendStatus(403); return; } res.sendStatus(200); });
FusionAuth shows the user a generic webhook error. To explain the limit, edit the [WebhookTransactionException] message in your theme's messages. For more information, see Theme Localization. The message applies to every webhook failure during a transaction, so reword the message to cover your other webhooks too.
To test the limit, log in as the same user from more browsers or private windows than the limit allows.
Let the User Pick a Session to End#
The session picker always lets the login finish. Your application then checks the session count on each protected request. When the user is over the limit, your application shows the other sessions and revokes the ones the user picks.
-
Shorten the access token lifetime. A revoked refresh token doesn't end the access token that the other device already holds. Set JWT duration on the Application's JWT tab to a few minutes, such as
300seconds, so the other device loses access soon after you revoke the session. -
Add middleware after your authentication middleware. The middleware lists the user's other sessions for the Application and redirects to a session picker when the count reaches the limit. The session list leaves out the current session, so the user can't end the session in use:
Check the session count on each request interface Device { id: string; deviceName: string; startInstant: string; ipAddress: string; } async function checkDeviceLimit(req: Request, res: Response, next: NextFunction) { const otherDevices = await getActiveDeviceList(req, res); if (otherDevices.length >= maxDeviceCount) { res.redirect(302, '/device-limit'); return; } next(); } // the user's other sessions for this application, without token values async function getActiveDeviceList(req: Request, res: Response): Promise<Device[]> { const currentRefreshTokenId = req.cookies[userToken]?.refresh_token_id; const { refreshTokens = [] } = (await apiClient.retrieveRefreshTokens(res.locals.userId)).response; return refreshTokens .filter((t) => t.applicationId === clientId && t.id !== currentRefreshTokenId) .map((t) => ({ id: t.id as string, deviceName: t.metaData?.device?.name ?? 'Unknown device', startInstant: new Date(t.startInstant as number).toUTCString(), ipAddress: t.metaData?.device?.lastAccessedAddress ?? '' })); } -
Render the list on the picker page, with the device name, start time, and IP address from each refresh token. When the user submits the form, revoke each selected refresh token with the Revoke Refresh Tokens API:
Revoke the selected sessions app.post("/device-limit", validateUserToken, async (req, res) => { const refreshTokenIds: string[] = [].concat(req.body.deviceIds ?? []); if (refreshTokenIds.length === 0) { res.redirect(302, '/device-limit'); return; } // only revoke tokens that belong to this user and application const ownDeviceIds = new Set((await getActiveDeviceList(req, res)).map((device) => device.id)); for (const refreshTokenId of refreshTokenIds.filter((id) => ownDeviceIds.has(id))) { await apiClient.revokeRefreshTokenById(refreshTokenId).catch((err) => console.error(err)); } res.redirect(302, '/account'); });
For the full application, including the session picker template, see the example repository. For the webhook approach, see the webhook example repository.
Related
Learn how to track and revoke application sessions in FusionAuth by tying each session to a refresh token.
Learn how to list a user's sessions and end the sessions from the Admin UI, the API, or automatically.
Learn how to set how long users stay logged in to FusionAuth and to your applications.
Learn about what each FusionAuth logout method ends, and how front-channel logout signs a user out of every application.