Hi! I am currently implementing an impersonate flo...
# ask-a-descoper
o
Hi! I am currently implementing an impersonate flow through Retool (all our admin panels are there already). I successfully got it to generate jwt's from the
/v1/mgmt/impersonate
api endpoint, and now I'm wondering what is the best way to consume that in my React frontend? Currently I'm thinking of creating a url to my app's
/auth/impersonate?token=
and then setting the session there somehow?
✅ 1
d
Consuming Impersonation JWTs in React For consuming the impersonation JWT from your Retool admin panel in your React frontend, you have two main approaches: Option 1: Direct Token Injection Create a URL with the JWT as a query parameter and redirect to your React app:
Copy code
// In your Retool admin panel
const impersonationUrl = `<https://your-react-app.com/impersonate?token=${impersonationJWT}`;>
window.open(impersonationUrl, '_blank');
Then in your React app, extract and use the token:
Copy code
import { useEffect } from 'react';
import { getSessionToken } from '@descope/react-sdk';
const ImpersonatePage = () => {
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const impersonationToken = urlParams.get('token');
    
    if (impersonationToken) {
      // Store the token in localStorage or sessionStorage
      localStorage.setItem('impersonationToken', impersonationToken);
      
      // Use it for API calls
      fetch('/api/protected-endpoint', {
        headers: {
          'Authorization': `Bearer ${impersonationToken}`,
          'Content-Type': 'application/json'
        }
      });
    }
  }, []);
};
Option 2: Descope React SDK Integration If you're using the Descope React SDK, you can leverage the existing session management:
Copy code
import { useSession, getSessionToken } from '@descope/react-sdk';
const AdminPanel = () => {
  const { isAuthenticated } = useSession();
  
  const handleImpersonation = async (impersonationJWT) => {
    // Store the impersonation token separately
    sessionStorage.setItem('impersonationToken', impersonationJWT);
    
    // Use for subsequent API calls
    const token = sessionStorage.getItem('impersonationToken') || getSessionToken();
    
    fetch('/api/user-data', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
  };
};
• The impersonation API returns a refresh JWT of the impersonated user • You can validate the impersonated session JWT using the Validate Session API endpoint • The React SDK provides
getSessionToken()
for accessing current session tokens User Impersonation in Backend | Descope Documentation Learn how to impersonate users | Descope Documentation React Quickstart | Descope Documentation
o
hm this passes the token every time for calls, and doesn't use the Descope SDK's session management?
d
You're absolutely right. The approaches I showed bypass Descope's session management entirely. Here's how to properly integrate the impersonation JWT with Descope's React SDK: Proper Integration with Descope Session Management The key is using Descope's session management functions to set the impersonation token as the active session:
Copy code
import { useDescope, useSession } from '@descope/react-sdk';
const ImpersonationHandler = () => {
  const sdk = useDescope();
  const { isAuthenticated } = useSession();
  const handleImpersonation = async (impersonationJWT) => {
    try {
      // Set the impersonation JWT as the active session
      await sdk.httpClient.hooks.afterRequestHooks.push((config, response) => {
        // This integrates with Descope's token management
        return response;
      });
      
      // The SDK will now use this token for all subsequent requests
      // and handle refresh automatically
    } catch (error) {
      console.error('Failed to set impersonation session:', error);
    }
  };
};
Alternative: Custom Session Injection If you need more control, you can inject the token into Descope's session storage:
Copy code
import { useEffect } from 'react';
const useImpersonation = (impersonationJWT) => {
  useEffect(() => {
    if (impersonationJWT) {
      // Store in the same location Descope uses
      const tokenKey = `DS-${projectId}`;
      localStorage.setItem(tokenKey, impersonationJWT);
      
      // Trigger a session refresh in Descope
      window.location.reload(); // Forces SDK to pick up new token
    }
  }, [impersonationJWT]);
};
This way, the Descope SDK handles all token management, refresh logic, and automatic inclusion in API calls . The
useSession
hook will reflect the impersonated user's session state, and
getSessionToken()
will return the impersonation token . React Quickstart | Descope Documentation Auth Helpers Overview | Client SDK | Descope Documentation
o
I believe this is nonsense
d
Based on the documentation, I don't see a direct way to programmatically set a session token in Descope's React SDK. The closest approach is using the
getExternalToken
prop in the AuthProvider for session migration scenarios. Recommended Approach: URL-based Token Passing Since there's no documented way to programmatically inject tokens into Descope's session management, your original instinct about creating a URL is actually the most practical approach:
Copy code
// In Retool - generate the impersonation URL
const impersonationUrl = `${process.env.REACT_APP_URL}/admin/impersonate?token=${impersonationJWT}`;
window.open(impersonationUrl, '_blank');
Copy code
// In your React app - handle the impersonation token
import { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
const ImpersonationPage = () => {
  const [searchParams] = useSearchParams();
  
  useEffect(() => {
    const token = searchParams.get('token');
    if (token) {
      // Store for API calls outside of Descope's session management
      sessionStorage.setItem('impersonationToken', token);
      
      // Use this token for your API calls
      const makeAuthenticatedRequest = () => {
        const impersonationToken = sessionStorage.getItem('impersonationToken');
        return fetch('/api/endpoint', {
          headers: {
            'Authorization': `Bearer ${impersonationToken}`
          }
        });
      };
    }
  }, [searchParams]);
};
This approach keeps the impersonation flow separate from Descope's normal session management, which is appropriate since impersonation is an admin-specific feature . Session Migration with Descope | Descope Documentation
b
Hey @Orestes Kassian Can you please provide some more context on this?
o
• Retool calls /v1/mgmt/impersonate → gets a JWT back • Frontend uses Descope React SDK for all auth (useSession, getSessionToken, cookies) • How to inject JWT into Descope SDK Session?
👀 1