Authenticator Apps (TOTP) via Backend SDKs

This guide is meant for developers that are NOT using Descope Flows to design login screens and authentication methods.

If you'd like to use Descope Flows, Quick Start should be your starting point.

Descope supports validating sign-up and sign-ins via Authenticator Applications which provide a Time-based One-time Password (TOTP). Google Authenticator, Microsoft Authenticator, and Authy are examples of authenticator apps. Descope generates the required QR code or key (also called a secret or seed) in order to configure new a new Authenticator.

Backend SDK

Install SDK

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

Import and initialize SDK

import DescopeClient from '@descope/node-sdk';
try{
    //  baseUrl="<URL>" // When initializing the Descope clientyou can also configure the baseUrl ex: https://auth.company.com  - this is useful when you utilize CNAME within your Descope project.
    const descopeClient = DescopeClient({ projectId: '__ProjectID__' });
} catch (error) {
    // handle the error
    console.log("failed to initialize: " + error)
}
 
// Note that you can handle async operation failures and capture specific errors to customize errors.
//     An example can be found here: https://github.com/descope/node-sdk?tab=readme-ov-file#error-handling

User Sign-Up

The first step for implementing TOTP authentication is sign-up. In this step the user registers their TOTP app with the authentication service. Descope will generate a TOTP key (also called a secret or seed) that will be entered into the end user's authenticator app so that TOTP codes can be successfully verified. The new end user will be registered after the full TOTP sign-up flow has been successfully completed.

// Args:
//    user: Optional user object to populate new user information.
const user = { "name": "Joe Person", "phone": "+15555555555", "email": "email@company.com"}
//    loginId: email or phone - becomes the unique ID for the user from here on and also used for delivery
const loginId = "email@company.com"
 
const resp = await descopeClient.totp.signUp(loginId, user);
if (!resp.ok) {
  console.log("Failed to initialize TOTP signup")
  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 initialized TOTP signup.")
  console.log(resp.data)
}

User Sign-In / Verify

For signing in, your application client must prompt the user for loginId, such as email or phone, and the code from the authenticator application. Your client will then call the verify function. Upon successful verification, the user will be logged in and the response will include the JWT information.

// Args:
//    loginId: email or phone - must be same as provided at the time of signup.
const loginId = "email@company.com"
//     code: code entered by the user from the authenticator application.
const code = "xxxx"
//    loginOptions (LoginOptions): this allows you to configure behavior during the authentication process.
const loginOptions = {
      "stepup": false,
      "mfa": false,
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }
//    refreshToken (optional): the user's current refresh token in the event of stepup/mfa
 
const resp = await descopeClient.totp.verify(loginId, code, loginOptions);
if (!resp.ok) {
  console.log("Failed to Sign-In via TOTP")
  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 signed in via TOTP. " + JSON.stringify(resp.data))
}

Update User

The update user call is used when you would like to associate a new authenticator method with an existing and authenticated user. You need to pass the refresh token or http request of an authenticated user. The update will work only if the user is authenticated.

// Args:
//    loginId: email, phone or username of the authenticated user
const loginId = "email@company.com"
//    refresh_token: string with the refresh token of the user. This should be extracted from cookies sent with the query.
const refresh_token = "xxxxxxxx"
 
const resp = await descopeClient.totp.update(loginId, refresh_token)
if (!resp.ok) {
  console.log("Failed to initialized updating user's TOTP")
  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 initialized updating user's TOTP: " + resp.data)
}

Session Validation

The final step of completing the authentication with Descope is to validate the user session. Descope provides rich session management capabilities, including configurable session timeouts and logout functions. You can find the details and sample code for backend session validation here.

Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?
Was this helpful?

On this page