Magic Link via Mobile SDKs

A magic link is a single-use link sent to the user for authentication (sign-up or sign-in) that validates their identity. The Descope service can send magic links via email or SMS texts.

The browser tab that is opened after clicking the magic link gets the authenticated session cookies. For example, consider a user that starts the login process on a laptop browser and gets a magic link delivered to their email inbox. When they click the email link, a new browser tab will open and they will be logged in on the new tab.

The magic link flow within Descope for mobile SDK

TriangleAlert

Alert

Consider using magic links when your users typically use only one device to access your application, and when opening new tabs is not a big inconvenience.

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 magic-link will be sent by email to email@company.com. To change the delivery method to send the magic-link as a text, you would change the deliveryMethod to sms within the below example.

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

// Args:
//    deliveryMethod: Delivery method to use to send magic link. 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")
//    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_magiclink"
 
do {
  try await Descope.magicLink.signUp(with: deliveryMethod, loginId: loginId, user: user, uri: uri)
  print("Successfully initiated Magic Link Sign Up")
} catch {
  print("Failed to initiate Magic Link 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 magic-link will be sent by email to email@company.com.

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

// Args:
//    deliveryMethod: Delivery method to use to send magic link. 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"
//    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_magiclink"
 
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.magicLink.signIn(with: deliveryMethod, loginId: loginId, uri: uri, options: signInOptions)
  print("Successfully initiated Magic Link Sign In")
} catch {
  print("Failed to initiate Magic Link 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 magic-link will be sent by email to email@company.com. To change the delivery method to send the magic-link as a text, 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 magic link. Supported values include DeliveryMethod.email or DeliveryMethod.sms
let deliveryMethod = DeliveryMethod.email
//    loginId: email or phone - 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_magiclink"
 
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.magicLink.signUpOrIn(with: deliveryMethod, loginId: loginId, uri: uri, options: signInOptions)
  print("Successfully initiated Magic Link Sign Up or In")
} catch {
  print("Failed to initiate Magic Link Sign Up or In")
  print(error)
}

User Verification

Once a user clicks the magic-link, your application must call the verify function. This means that this function needs to be called from your application when the user clicks the magiclink. The function call will return all the the necessary JWT tokens and claims and user information in the resp dictionary. The sessionJwt within the resp is needed for session validation.

// Args:
//  token:  URL parameter containing the magic link token for example, http://auth.company.com/api/verify_magiclink?t=token.
let token = "xxxx"
 
do {
  let descopeSession = try await Descope.magicLink.verify(token: token)
  print("Successfully verified Magic Link Token")
  print(descopeSession as Any)
} catch {
  print("Failed to verify Magic Link Token")
  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 magic 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_magiclink"
//    refreshJwt: The refreshJwt of the user to be updated
let refreshJwt = "xxxxxx"
 
do {
  try await Descope.magicLink.updateEmail(email, loginId: loginId, uri: uri, refreshJwt: refreshJwt)
  print("Successfully initiated Magic Link Email Update")
} catch {
  print("Failed to initiate Magic Link 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 magic link will be sent via the sms delivery method. Once the update phone function has been called, you will need to verify the token 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"
//    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_magiclink"
//    refreshJwt: The refreshJwt of the user to be updated
let refreshJwt = "xxxxxx"
 
do {
  try await Descope.magicLink.updatePhone(phone, with: .sms, loginId: loginId, uri: uri, refreshJwt: refreshJwt)
  print("Successfully started Magic Link Phone Update")
} catch {
  print("Failed to initiate Magic Link 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