Maintaining a Single Session Per User

Overview

Implementing a single-active-session policy provides greater control over user activity and strengthens application security.

Applies To
  • Sessions
  • Auth0 Actions
  • User Management
Cause

Some users may have many established sessions they no longer need, which can compromise application security if a bad actor gains access to cookies pointing to older, active sessions.

Solution

Using Auth0 Actions, bind a new Action to the Post-Login Trigger that uses the Auth0 Management API to look up all active sessions for the user logging in and delete all sessions associated with the user besides the session that was just established.

Here is the code implementation on how this can be done:

/**
* @param {Event} event - Details about the user and the context in which they are logging in.
* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
*/
exports.onExecutePostLogin = async (event, api) => {
  const ManagementClient = require('auth0').ManagementClient;

  const managementAPI = new ManagementClient({
    domain: event.secrets.domain,
    clientId: event.secrets.clientId,
    clientSecret: event.secrets.clientSecret
  })

  const response = await managementAPI.users.sessions.list(event.user.user_id);
  const listSessions = response.response.sessions;

  for (let i = 0; i < listSessions.length; i++) {
    let sessionID = listSessions[i].id;

    if (sessionID != event?.session?.id) {
      await managementAPI.sessions.delete(sessionID);
    }
  }
}

// /**
// * @param {Event} event - Details about the user and the context in which they are logging in.
// * @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
// */
// exports.onContinuePostLogin = async (event, api) => {
// }

Ensure that the domain, clientId, and clientSecret secrets are set. The domain should be the tenant's canonical or custom domain, without any paths or  https:// prefixes. The clientId and clientSecret is from an Application that needs to be configured in the tenant. This Application should be an M2M application, with Auth0 Management API authorization enabled in the APIs section of the Application settings in the Auth0 Dashboard.

 

NOTE: This action uses the management API for every login attempt, which can be a bottleneck for high-load tenants regarding rate limits. More information can be found in Rate Limit Configurations documentation.

Also, these APIs (/api/v2/sessions/*, /api/v2/users/{user_id}, and /api/v2/users/{user_id}/sessions) are only available on Enterprise plans. An Enterprise plan is required to utilize this Action. The M2M application used in the Action's secrets must be granted read:sessions" and "delete:sessions permissions for the Management API.

Recommended content

No recommended content found...