OTP Authentication with Mobile SDKs

A one-time password (OTP) is an automatically generated string sent to the user during the onboarding (sign-up or sign-in) process to authenticate that user. The OTP can be sent to an email address or a mobile phone as a text. A typical method for implementing OTP has two sets of functionality you need to program: user interaction and session verification.

Use Cases

  1. New user signup: The following actions must be completed, first User Sign-Up then User Verification
  2. Existing user signin: The following actions must be completed, first User Sign-In then User Verification
  3. Sign-Up or Sign-In (Signs up a new user or signs in an existing user): The following actions must be completed, first User Sign-Up or Sign-In then User Verification

Client SDK

Install SDK

// 1. Within XCode, go to File > Add Packages
// 2. Search for the URL of the git repo: https://github.com/descope/swift-sdk
// 3. Configure your desired dependency rule
// 4. Click Add Package

Import and initialize SDK

import DescopeKit
import AuthenticationServices
 
do {
    Descope.setup(projectId: "__ProjectID__")
    print("Successfully initialized Descope")
} catch {
    print("Failed to initialize Descope")
    print(error)
}

User Sign-Up

For registering a new user, your application should accept user information, including an email or phone number used for verification. In this sample code, the OTP verification will be sent by email to email@company.com. To change the delivery method to send the OTP verification as a Text Message (SMS), you would change the deliveryMethod to sms within the below example.

Note that signup is not complete without the user verification step below.

// Args:
//    deliveryMethod: Delivery method to use to send OTP. Supported values include DeliveryMethod.email or DeliveryMethod.sms
let deliveryMethod = DeliveryMethod.email
//    loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
let loginId = "email@company.com"
//    user: Optional user object to populate new user information.
let user = User("name": "Joe Person", "phone": "+15555555555", "email": "email@company.com")
 
do {
  try await Descope.otp.signUp(with: deliveryMethod, loginId: loginId, user: user)
  print("Successfully initiated OTP Sign Up")
} catch {
  print("Failed to initiate OTP Sign Up")
  print(error)
}

User Sign-In

For authenticating a user, your application should accept the user's identity (typically an email address or phone number). In this sample code, the OTP verification will be sent by email to email@company.com.

Note that signin is not complete without the user verification step below.

// Args:
//    deliveryMethod: Delivery method to use to send OTP. Supported values include DeliveryMethod.email or DeliveryMethod.sms
let deliveryMethod = DeliveryMethod.email
//    loginId: email or phone - the loginId of the user
let loginId = "email@company.com"
 
guard let session = Descope.sessionManager.session else { return }
var signInOptions: [SignInOptions] = [
    .customClaims(["name": "{{user.name}}"]),
    .mfa(refreshJwt: session.refreshJwt),
    .stepup(refreshJwt: session.refreshJwt)
]
 
do {
  try await Descope.otp.signIn(with: deliveryMethod, loginId: loginId, options: signInOptions)
  print("Successfully initiated OTP Sign In")
} catch {
  print("Failed to initiate OTP Sign In")
  print(error)
}

User Sign-Up or Sign-In

For signing up a new user or signing in an existing user, you can utilize the signUpOrIn functionality. Only user loginId is necessary for this function. In this sample code, the OTP verification will be sent by email to email@company.com. To change the delivery method to send the OTP verification as a Text Message (SMS), you would change the deliveryMethod to sms within the below example.

Note that signUpOrIn is not complete without the user verification step below.

// Args:
//    deliveryMethod: Delivery method to use to send OTP. Supported values include DeliveryMethod.email or DeliveryMethod.sms
let deliveryMethod = DeliveryMethod.email
//    loginId: email or phone - the loginId of the user
let loginId = "email@company.com"
 
guard let session = Descope.sessionManager.session else { return }
var signInOptions: [SignInOptions] = [
    .customClaims(["name": "{{user.name}}"]),
    .mfa(refreshJwt: session.refreshJwt),
    .stepup(refreshJwt: session.refreshJwt)
]
 
do {
  try await Descope.otp.signUpOrIn(with: deliveryMethod, loginId: loginId, options: signInOptions)
  print("Successfully initiated OTP Sign Up or In")
} catch {
  print("Failed to initiate OTP Sign Up or In")
  print(error)
}

User Verification

The next step in authenticating the user is to verify the code entered by the user, using OTP verify code function. The function will return all the necessary JWT tokens, claims and user information. You can use the JWT tokens for session validation in your application middleware or app server for every route needs an authenticated user.

// Args:
//    deliveryMethod: Delivery method to use to send OTP. Supported values include DeliveryMethod.email or DeliveryMethod.sms
let deliveryMethod = DeliveryMethod.email
//   loginId (str): The loginId of the user being validated
let loginId = "email@company.com"
//   code (str): The authorization code enter by the end user during signup/signin
let code = "xxxx"
 
do {
  let descopeSession = try await Descope.otp.verify(with: deliveryMethod, loginId: loginId, code: code)
  print("Successfully verified OTP Code")
  print(descopeSession as Any)
} catch DescopeError.wrongOTPCode {
    print("Failed to verify OTP Code: ")
    print("Wrong code entered")
} catch {
    print("Failed to verify OTP Code: ")
    print(error)
}

Update Email

The Descope SDK allows for you to update user's email address. With this function, you will pass the user's loginId and the new email address you want associated to the user. In order to verify the email address, the OTP code will be sent via the email delivery method. Once the update email function has been called, the user will need to verify with the sent OTP code before the email address will be updated.

// Args:
//    email: the new email address you want to associate with the user
let email = "newEmail@company.com"
//    loginId: email or phone - the loginId of the user
let loginId = "email@company.com"
//    refreshJwt: The refreshJwt of the user to be updated
let refreshJwt = "xxxxxx"
 
do {
  try await Descope.otp.updateEmail(email, loginId: loginId, refreshJwt: refreshJwt)
  print("Successfully initiated OTP Email Update")
} catch {
  print("Failed to initiate OTP Email Update")
  print(error)
}

Update Phone

The Descope SDK allows for you to update user's phone number. With this function, you will pass the user's loginId and the new phone number you want associated to the user. In order to verify the phone number, the OTP code will be sent via the sms delivery method. Once the update phone function has been called, the user will need to verify with the sent OTP code before the phone number will be updated.

// Args:
//    phone: the new phone number you want to associate with the user
let phone = "+12222222222"
//    loginId: email or phone - the loginId of the user
let loginId = "email@company.com"
//    refreshJwt: The refreshJwt of the user to be updated
let refreshJwt = "xxxxxx"
 
do {
  try await Descope.otp.updatePhone(phone, with: .sms, loginId: loginId, refreshJwt: refreshJwt)
  print("Successfully initiated OTP Phone Update")
} catch {
  print("Failed to initiate OTP Phone Update")
  print(error)
}

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 client 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