Enchanted Link via Mobile SDKs

An enchanted link is a single-use link sent to the user for authentication (sign-up or sign-in) that validates their identity. The Descope service sends enchanted links via email.

Enchanted links are an enhanced version of magic links. Enchanted links enable users to start the login process on one device (the originating device) while clicking the enchanted link on a different device. When the user clicks the correct link, their session on the originating device is validated, and they are logged in. A special security feature of enchanted link is that the end-user needs to pick the correct link from the three links delivered to them.

The enchanted link flow within Descope for mobile SDK

TriangleAlert

Alert

Enchanted links are user friendly since the user does not have to switch tabs or applications to log in. The browser tab they initiated login from is the only tab they need to use.

Use Cases

  1. New user signup: The following actions must be completed, first User Sign-Up, then within the same route begin Polling for a valid session, and when the enchanted link is clicked User Verification
  2. Existing user signin: The following actions must be completed, first User Sign-In, then within the same route begin Polling for a valid session, and when the enchanted link is clicked 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 within the same route begin Polling for a valid session, and when the enchanted link is clicked 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 client should accept user information, including an email or phone number used for verification. The application client should send this information to your application server. In this sample code, the enchanted link will be sent by email to email@company.com. The signup call returns a pendingRef and a linkId. Display the linkId to end user from your application so that they can click on the correct link in the email that they receive. Then your application will utilize the pendingRef to poll for verification status on the originating device.

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

// Args:
//    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")
//    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
let uri = "http://auth.company.com/api/verify_enchantedlink"
 
do {
  let enchantedResponse = try await Descope.enchantedLink.signUp(loginId: loginId, user: user, uri: uri)
  print("Successfully initiated Enchanted Sign Up")
  print("Enchanted Link linkId: " + enchantedResponse!.linkId)
  print("Enchanted Link pendingRef: " + enchantedResponse!.pendingRef)
} catch {
  print("Failed to initiate Enchanted Sign Up")
  print(error)
}

User Sign-in

For authenticating a user, your application client should accept the user's identity (typically an email address or phone number). In this sample code, the enchanted link will be sent by email to email@company.com. The signin call returns a pendingRef and a linkId. Display the linkId to end user from your application so that they can click on the correct link in the email that they receive. Then your application will utilize the pendingRef to poll for verification status on the originating device.

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

// Args:
//    loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
let loginId = "email@company.com"
//    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
let uri = "http://auth.company.com/api/verify_enchantedlink"
 
guard let session = Descope.sessionManager.session else { return }
var signInOptions: [SignInOptions] = [
    .customClaims(["name": "{{user.name}}"]),
    .mfa(refreshJwt: session.refreshJwt),
    .stepup(refreshJwt: session.refreshJwt)
]
 
do {
  let enchantedResponse = try await Descope.enchantedLink.signIn(loginId: loginId, uri: uri, options: signInOptions)
  print("Successfully initiated Enchanted Link Sign In")
  print("Enchanted Link linkId: " + enchantedResponse!.linkId)
  print("Enchanted Link pendingRef: " + enchantedResponse!.pendingRef)
} catch {
  print("Failed to initiate Enchanted Sign Up")
  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. In this sample code, the enchanted link will be sent by email to email@company.com. The signin call returns a pendingRef and a linkId. Display the linkId to end user from your application so that they can click on the correct link in the email that they receive. Then your application will utilize the pendingRef to poll for verification status on the originating device.

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

// Args:
//    loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
let loginId = "email@company.com"
//    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
let uri = "http://auth.company.com/api/verify_enchantedlink"
 
guard let session = Descope.sessionManager.session else { return }
var signInOptions: [SignInOptions] = [
    .customClaims(["name": "{{user.name}}"]),
    .mfa(refreshJwt: session.refreshJwt),
    .stepup(refreshJwt: session.refreshJwt)
]
 
do {
  let enchantedResponse = try await Descope.enchantedLink.signUpOrIn(loginId: loginId, uri: uri, options: signInOptions)
  print("Successfully initiated Enchanted Link Sign Up or In")
  print("Enchanted Link linkId: " + enchantedResponse!.linkId)
  print("Enchanted Link pendingRef: " + enchantedResponse!.pendingRef)
} catch {
  print("Failed to initiate Enchanted Sign Up or in")
  print(error)
}

User Verification

Call the verify function from your verify url. This means that this function needs to be called when the user clicks the enchanted link. If the token is valid, the user will be authenticated and session returned to the polling thread (see next step). This should be implemented from your web client or backend sdk when the link is clicked from the email received. The mobile application will then poll for a session.

Polling for valid session

On the route where you initialized the signIn, signUp, or signUpOrIn, you need to repeatedly poll for a valid session. get_session(token) is called repeatedly until the user clicks the enchanted link URL they received, so that the session on the initiating device can be directed to your desired page.

// Args:
//    pendingRef: Reference token received from signup or signin call.
let pendingRef = "xxxxx"
 
do {
  let descopeSession = try await Descope.enchantedLink.pollForSession(pendingRef: enchantedResponse!.pendingRef, timeout: 180)
  print("Successfully completed polling flow")
  print(descopeSession as Any)
} catch {
  print("Failed to complete polling flow")
  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 enchanted link will be sent via the email delivery method. Once the update email function has been called, you will need to verify the token 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"
//    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
let uri = "http://auth.company.com/api/verify_enchantedlink"
//    refreshJwt: The refreshJwt of the user to be updated
let refreshJwt = "xxxxxx"
 
do {
  let enchantedResponse = try await Descope.enchantedLink.updateEmail(email, loginId: loginId, uri: uri, refreshJwt: refreshJwt)
  print("Successfully started Enchanted Link Email Update")
  print("Enchanted Link linkId: " + enchantedResponse!.linkId)
  print("Enchanted Link pendingRef: " + enchantedResponse!.pendingRef)
} catch {
  print("Successfully started Enchanted Link Email 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