Deployments and TestingUser Impersonation

User Impersonation with Management SDKs

The management SDK requires a management key, which can be generated here.

You can use Descope management SDK for user impersonation operations.

Install SDK

Terminal
npm i --save @descope/node-sdk

Import and initialize Management SDK

import DescopeClient from '@descope/node-sdk';

const managementKey = "xxxx"

try{
    //  baseUrl="<URL>" // When initializing the Descope clientyou can also configure the baseUrl ex: https://auth.company.com  - this is useful when you utilize a custom domain within your Descope project.
    const descopeClient = DescopeClient({ projectId: '__ProjectID__', managementKey: managementKey });
} catch (error) {
    // handle the error
    console.log("failed to initialize: " + error)
}

Impersonate User

Note

You can also use our /impersonation API to impersonate a user.

This operation allows administrators to impersonate an existing user. The impersonator user must have the impersonation permission in order for this request to work. On success, the response will be a refresh JWT of the impersonated user.

// Args:
//   impersonatorId (str): The login_id of the user that's doing the impersonating.
//   loginId (str): The login_id of the user that's to be impersonated.
//   validateConsent (boolean): Whether to check if the user to be impersonated has given consent
//   customClaims (object): Optional, custom claims to be added to the impersonated user's JWT
//   tenantId (str): Optional, one of the tenants the impersonated user belongs to
//   refreshDuration (number): Optional, duration in seconds for which the new JWT will be valid
const impersonatorId = "admin@company.com"
const loginId = "user@company.com"
const validateConsent = true
const customClaims = {"key1": "value1"}
const tenantId = "your-tenant-id"
const refreshDuration = 3600

const resp = await descopeClient.management.jwt.impersonate(
  impersonatorId,
  loginId,
  validateConsent,
  customClaims,
  tenantId,
  refreshDuration
);
if (!resp.ok) {
  console.log("Failed to impersonate user")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully impersonated user")
  console.log(resp.data)
}

Impersonate User with Step-Up

Note

You can also use our /impersonate/stepup API to impersonate a user with step-up authentication.

This operation allows administrators to impersonate an existing user and receive a step-up session JWT for the impersonated user. The impersonator user must have the impersonation permission in order for this request to work. On success, the response will be a session JWT of the impersonated user.

# Args:
#   impersonator_id (str): The login_id of the user that's doing the impersonating.
#   login_id (str): The login_id of the user that's to be impersonated.
#   validate_consent (boolean): Whether to check if the user to be impersonated has given consent
#   custom_claims (dict): Optional, custom claims to be added to the impersonated user's JWT
#   tenant_id (str): Optional, one of the tenants the impersonated user belongs to
#   refresh_duration (int): Optional, duration in seconds for which the new JWT will be valid
#   stepup (bool): Whether to generate a step-up token for the impersonated user

try:
  session_jwt = descope_client.mgmt.jwt.impersonate(
    impersonator_id="admin@company.com",
    login_id="user@company.com",
    validate_consent=True,
    custom_claims={"key1": "value1"},
    tenant_id="your-tenant-id",
    refresh_duration=3600,
    stepup=True
  )
  print("Successfully impersonated user with step-up.")
  print(session_jwt)
except AuthException as error:
  print("Unable to impersonate user with step-up.")
  print("Status Code: " + str(error.status_code))
  print("Error: " + str(error.error_message))

Stop User Impersonation

Note

You can also use our /stop-impersonation API to impersonate a user.

This feature enables users to seamlessly switch back to their original account during an impersonation session.

// Args:
//   jwt (string): The impersonation JWT to be stopped (required).
//   customClaims (object): Optional, custom claims to add to the new JWT
//   selectedTenant (string): Optional, the tenant ID to set on the DCT claim
//   refreshDuration (number): Optional, duration in seconds for which the new JWT will be valid
const jwt = "xxxxxxxxx"
const customClaims = {"role": "admin"}
const selectedTenant = "tenant-123"
const refreshDuration = 3600

const resp = await descopeClient.management.jwt.stopImpersonation(
  jwt,
  customClaims,
  selectedTenant,
  refreshDuration
);
if (!resp.ok) {
  console.log("Failed to stop impersonation")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully stopped impersonation. New JWT issued:")
  console.log(resp.data.jwt)
}
Was this helpful?

On this page