Client SDK Auth Helpers

The Auth class is a crucial component of the Descope SDK, handling key user authentication operations. This class is designed to execute essential functions such as fetching user details, fetching and refreshing sessions, and logging out users.

Before using the Auth Helper Functions, make sure to import and initialize the relevant SDK.

Manage Session

If project settings are configured to manage session token in cookies, Descope services will automatically set the session token in the DS cookie as a Secure and HttpOnly cookie. In this case, the session token will not be stored in the browser and will not be accessible to the client-side code using these session management functions.

The useSession functions retrieve information about the current user session.

They return the following details:

Objects

  • sessionToken: The JWT for the current session.

Booleans

  • isAuthenticated: Boolean for the authentication state of the current user session.
  • isSessionLoading: Boolean for the loading state of the session. Can be used to display a "loading" message while the session is still loading.

Additional helper functions

  • getSessionToken: The JWT for the current session.
  • getRefreshToken: The refresh JWT for the current session.

Limited to Non-Cookie Storage

The getRefreshMethod function will not work if refresh tokens are stored in httpOnly cookies, as they cannot be accessed from the frontend.

  • isSessionTokenExpired: Boolean for checking if a given session token is expired.
  • isRefreshTokenExpired: Boolean for checking if a refresh token is expired.
  • getJwtRoles: Get current roles from an existing session token. Provide tenant id for specific tenant roles.
  • getJwtPermissions: Get current permissions from an existing session token. Provide tenant id for specific tenant permissions.
  • getCurrentTenant: Get current tenant id from an existing session token (from the dct claim).
import { useSession, getSessionToken, getRefreshToken, isSessionTokenExpired, isRefreshTokenExpired, 
        getJwtRoles, getJwtPermissions, getCurrentTenant } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
  const { isAuthenticated, isSessionLoading, sessionToken } = useSession();
 
  const refreshToken = getRefreshToken();
  const sessionTokenFromFunction = getSessionToken();
 
  const isRefreshTokenExpired = isRefreshTokenExpired(refreshToken);
  const isSessionTokenExpired = isSessionTokenExpired(sessionTokenFromFunction);
 
  const jwtRoles = getJwtRoles(token = sessionToken, tenant = '<tenant-id>');
  const jwtPermissions = getJwtPermissions(token = sessionToken, tenant = '<tenant-id>');
  const currentTenant = getCurrentTenant(token = sessionToken);
 
  if isAuthenticated { 
    return (
      <>
        <p>You are authenticated.</p>
      </>
    );
  }
};

Core SDK Functions

The following functions are part of the Core SDK (inherited by all client SDKs) and can be accessed through the useDescope() hook. These functions provide additional functionality for session management, tenant operations, and user data retrieval.

Available Functions

  • refresh: Refreshes a session token using a valid refresh token
  • selectTenant: Selects a tenant for the current session. You can use this function to switch the dct claim in the JWT token.
  • myTenants: Returns tenant information for the current user
  • history: Returns the current user's authentication history
  • logout: Logs out the current session
  • logoutAll: Logs out all sessions for the current user
  • me: Returns the current user details
  • isJwtExpired: Checks if the given JWT is still valid (does NOT check signature)
  • getTenants: Returns the list of tenants in the given JWT (does NOT check signature)

Usage Examples

import { useDescope } from '@descope/react-sdk';
 
const App = () => {
  const sdk = useDescope();
 
  const handleRefresh = async () => {
    try {
      const result = await sdk.refresh();
      console.log('Session refreshed:', result);
    } catch (error) {
      console.error('Refresh failed:', error);
    }
  };
 
  const handleSelectTenant = async (tenantId) => {
    try {
      await sdk.selectTenant(tenantId);
      console.log('Tenant selected');
    } catch (error) {
      console.error('Tenant selection failed:', error);
    }
  };
 
  const getMyTenants = async () => {
    try {
      const tenants = await sdk.myTenants(true); // Get selected tenant only
      console.log('My tenants:', tenants);
    } catch (error) {
      console.error('Failed to get tenants:', error);
    }
  };
 
  const getUserHistory = async () => {
    try {
      const history = await sdk.history();
      console.log('User history:', history);
    } catch (error) {
      console.error('Failed to get history:', error);
    }
  };
 
  const checkJwtExpiry = (token) => {
    const isExpired = sdk.isJwtExpired(token);
    console.log('JWT expired:', isExpired);
  };
 
  const getTenantList = (token) => {
    const tenants = sdk.getTenants(token);
    console.log('Tenants in JWT:', tenants);
  };
 
  return (
    <div>
      <button onClick={handleRefresh}>Refresh Session</button>
      <button onClick={() => handleSelectTenant('tenant-id')}>Select Tenant</button>
      <button onClick={getMyTenants}>Get My Tenants</button>
      <button onClick={getUserHistory}>Get User History</button>
    </div>
  );
};

Handling Authentication State Changes

Descope provides event listeners to track session and user state changes dynamically. These functions can be accessed through useDescope().

Event Functions

  • onSessionTokenChange(newSession, oldSession): Triggers when the session token changes.
  • onIsAuthenticatedChange(isAuthenticated): Fires when authentication status changes.
  • onUserChange(newUser, oldUser): Triggers when user data updates.
import { useEffect, useState } from 'react';
import { useDescope } from '@descope/react-sdk';
 
const App = () => {
  const [user, setUser] = useState<User>();
  const [session, setSession] = useState<string>();
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  
  const sdk = useDescope();
 
  useEffect(() => {
    const unsubscribeTokenChange = sdk.onSessionTokenChange(setSession);
    const unsubscribeAuthChange = sdk.onIsAuthenticatedChange(setIsAuthenticated);
    const unsubscribeUserChange = sdk.onUserChange(setUser);
 
    return () => {
      unsubscribeTokenChange();
      unsubscribeAuthChange();
      unsubscribeUserChange();
    };
  }, [sdk]);
 
  return <p>Listening for authentication changes...</p>;
};

Manage User

The useUser and me functions return information about the currently authenticated user. These methods are used when you need to fetch or display user-related data in your application.

These functions returns the following details:

Objects

  • user: object that contains the following user attributes:
    • email: Email address associated to the user.
    • name: Name associated to the user.
    • givenName: Given name associated to the user.
    • middleName: Middle name associated to the user.
    • familyName: Family name associated to the user.
    • phone: Phone number associated to the user.
    • loginIds: An array of loginIds associated to the user.
    • userId: The user's unique Descope generated userId.
    • verifiedEmail: Boolean whether the email address for the user has been verified.
    • verifiedPhone: Boolean whether the phone number for the user has been verified.
    • picture: The base64 encoded image if the user has an image associated to them.
    • roleNames: An array of roles associated to the user.
    • userTenants: An array of tenant names and IDs associated to the user.
    • createTime: The time that the user was created.
    • totp: Boolean whether the user has TOTP login associated with it.
    • saml: Boolean whether the user has SAML login associated with it.
    • oauth: Boolean whether the user has OAuth login associated with it.

Booleans

  • isUserLoading: Boolean for whether the user object is currently loading.

Note

useDescope, useSession, and useUser should be used inside AuthProvider context, and will throw an exception if this requirement is not met

import { useUser } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
  const { user, isUserLoading } = useUser();
  return (
    <>
      <p>Hello {user.name}</p>
    </>
  );
};

Refresh Session

In the case that the browser has a valid refresh token on storage/cookie, the user should get a valid session token (i.e. user should be logged-in). For this reason, it is common to call the refresh function after sdk initialization. Refresh returns a session token, so if autoRefresh is set to true, the sdk will automatically continue to refresh the token.

useDescope is a React hook that retrieves the Descope SDK for further operations related to authentication. This includes the refresh operation, as shown in the React and Next.js examples below.

Note

useSession triggers a single request to the Descope backend to attempt to refresh the session. If you don't useSession on your app, the session will not be refreshed automatically. If your app does not require useSession, you can trigger the refresh manually by calling refresh from the useDescope hook:

import { useSession, useUser, useDescope } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
  const { isAuthenticated, isSessionLoading } = useSession();
  const { refresh } = useDescope();
  useEffect(() => {
    refresh();
  }, [refresh]);

Refresh User Data in JWT

The useUser and me functions not only return user information but also refresh the user details stored in the JWT token.

When user attributes are updated on the backend (such as through SCIM, admin operations, or other user management processes), calling these functions in the SDK will fetch the latest user data and update the current JWT token with the updated values.

Example Use Cases

import { useUser } from '@descope/react-sdk';
 
const UserProfile = () => {
  const { user, isUserLoading } = useUser();
  
  // This will show updated user data after SCIM provisioning
  // or admin changes, even without re-login
  return (
    <div>
      <h1>Welcome, {user.name}</h1>
      <p>Email: {user.email}</p>
      <p>Department: {user.customAttributes?.department}</p>
    </div>
  );
};

Logout

Logs out the currently authenticated user. This method invalidates the user's current JWT tokens and ends their session. This function is typically used when the user chooses to log out of your application.

useDescope is a React hook that retrieves the Descope SDK for further operations related to authentication. This includes the logout operation, as shown in the React, Next.js, and Vue examples below.

import { useDescope } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
	const { logout } = useDescope();
 
	const handleLogout = useCallback(() => {
		logout();
	}, [logout]);
 
  return (
    <>
      <button onClick={handleLogout}>Logout</button>
    </>
  );
};

Logout All

This will sign the user out of all the devices they are currently signed-in with. Successfully executing this endpoint will invalidate all user's refresh tokens. Response will include all user tokens and fields empty, so client will remove cookies as well.

useDescope is a React hook that retrieves the Descope SDK for further operations related to authentication. This includes the logoutAll operation, as shown in the React, Next.js, and Vue examples below.

import { useDescope } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
	const { logoutAll } = useDescope();
 
	const handleLogout = useCallback(() => {
		logoutAll();
	}, [logoutAll]);
 
  return (
    <>
      <button onClick={handleLogout}>logoutAll</button>
    </>
  );
};
Was this helpful?

On this page