Magic Link

This authentication guide is meant for developers that are NOT using Descope to design login screens and authentication flows. If you’d like to use Descope Flows, Quick Start should be your starting point.

Introduction

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.


This image shows the magic link flow within Descope for backend SDK.


left parenthesis
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.
right parenthesis


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

Install SDK

NodeJSPythonGoJava
npm i --save @descope/node-sdk
pip3 install descope
go get github.com/descope/go-sdk
// Include the following in your `pom.xml` (Maven)
<dependency>
    <artifactId>java-sdk</artifactId>
    <groupId>com.descope</groupId>
    <version>sdk-version</version> // Check https://github.com/descope/descope-java/releases for the latest versions
</dependency>

Import and initialize SDK

NodeJSPythonGoJava
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
from descope import (
    REFRESH_SESSION_TOKEN_NAME,
    SESSION_TOKEN_NAME,
    AuthException,
    DeliveryMethod,
    DescopeClient,
    AssociatedTenant,
    RoleMapping,
    AttributeMapping,
    LoginOptions
)
try:
    # You can configure the baseURL by setting the env variable Ex: export DESCOPE_BASE_URI="https://auth.company.com  - this is useful when you utilize CNAME within your Descope project."
    descope_client = DescopeClient(project_id='__ProjectID__')
except Exception as error:
    # handle the error
    print ("failed to initialize. Error:")
    print (error)
import "github.com/descope/go-sdk/descope"
import "github.com/descope/go-sdk/descope/client"

// Utilizing the context package allows for the transmission of context capabilities like cancellation
//      signals during the function call. In cases where context is absent, the context.Background()
//      function serves as a viable alternative.
//      Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
import (
	"context"
)

// DescopeBaseURL // within the client.Config, you can also configure the baseUrl ex: https://auth.company.com  - this is useful when you utilize CNAME within your Descope project.

descopeClient, err := client.NewWithConfig(&client.Config{ProjectID:"__ProjectID__"})
if err != nil {
    // handle the error
    log.Println("failed to initialize: " + err.Error())
}
import com.descope.client.Config;
import com.descope.client.DescopeClient;

var descopeClient = new DescopeClient(Config.builder().projectId("__ProjectID__").build());

User Sign-Up

For registering a new user, your application client 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 delivery_method to sms within the below example.

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

NodeJSPythonGoJava
// 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 loginId for the user from here on and also used for delivery
const 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'
const uri = "http://auth.company.com/api/verify_magiclink"
//    deliveryMethod: Delivery method to use to send magic-link. Supported values include "email" or "sms"
const deliveryMethod = "email"
//    signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }

const resp = await descopeClient.magicLink.signUp[deliveryMethod](loginId, uri, user, signUpOptions)
if (!resp.ok) {
  console.log("Failed to initialize signup flow")
  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 signup flow")
}
# Args:
#   user: Optional user object to populate new user information.
user = { "name": "Joe Person", "phone": "+15555555555", "email": "email@company.com"}
#   login_id: email or phone - becomes the loginId for the user from here on and also used for delivery
login_id = "email@company.com"
#   delivery_method: Method used to deliver the magic-link. Supported delivery methods - DeliveryMethod.SMS, DeliveryMethod.EMAIL
delivery_method = DeliveryMethod.EMAIL
#   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'
uri = "http://auth.company.com/api/verify_magiclink"
#   signup_options (SignUpOptions): this allows you to configure behavior during the authentication process.
signup_options = {
      "custom_claims": {"claim": "Value1"},
      "template_options": {"option": "Value1"}
    }

try:
  resp = descope_client.magiclink.sign_up(method=delivery_method, login_id=login_id, uri=uri, user=user, signup_options=signup_options)
  print ("Successfully initialized signup flow")
  print (resp)
except AuthException as error:
  print ("Failed to initialize signup flow")
  print ("Status Code: " + str(error.status_code))
  print ("Error: " + str(error.error_message))
// Args:
//  ctx: context.Context - Application context for the transmission of context capabilities like
//        cancellation signals during the function call. In cases where context is absent, the context.Background()
//        function serves as a viable alternative.
//        Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
//  deliveryMethod: Method used to deliver the MagicLink. Supported delivery methods - descope.MethodEmail or descope.MethodSMS
deliveryMethod := descope.MethodEmail
//  loginID: email or phone - Used as the unique ID for the user from here on and also used for delivery
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'
URI := "http://auth.company.com/api/verify_magiclink"
//  user: Optional user object to populate new user information.
user := &descope.User{Name:"Joe", Email:"email@company.com", Phone:"+15555555555"}
//    signUpOptions: this allows you to configure behavior during the authentication process.
signUpOptions := &descope.LoginOptions{
    Stepup: true,
    MFA: true,
    CustomClaims: map[string]any{}{"test": "testClaim"},
    TemplateOptions: map[string]any{"option": "Value1"}
  }

err := descopeClient.Auth.MagicLink().SignUp(ctx, deliveryMethod, loginID, URI, user, signUpOptions)
if (err != nil){
  fmt.Println("Failed to initialize signup flow: ", err)
} else {
  fmt.Println("Successfully initialized signup flow")
}
// If configured globally, the redirect URI is optional. If provided however, it will be used
// instead of any global configuration

// Every user must have a loginID. All other user information is optional
String loginId = "email@company.com";
User user = User.builder()
    .name("Joe Person")
    .phone("+15555555555")
    .email(loginId)
    .build();
var signUpOptions = SignupOptions.builder()
        .customClaims(
           new HashMap<String, Object>() {{
                put("custom-key1", "custom-value1");}}
        )
        .templateOptions(
           new HashMap<String, String>() {{
                put("option", "Value1");}}
        )
				.build();

MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();

try {
  String uri = "http://auth.company.com/api/verify_magiclink";
  String maskedAddress = mls.signUp(DeliveryMethod.EMAIL, loginId, uri, user, signUpOptions);

} catch (DescopeException de) {
  // Handle the 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 magic-link will be sent by email to "email@company.com".

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

NodeJSPythonGoJava
// Args:
//    loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
const 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'
const uri = "http://auth.company.com/api/verify_magiclink"
//    deliveryMethod: Delivery method to use to send magic-link. Supported values include "email" or "sms"
const deliveryMethod = "email"
//    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.magicLink.signIn[deliveryMethod](loginId, uri, loginOptions)
if (!resp.ok) {
  console.log("Failed to initialize signin flow")
  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 signin flow")
}
# Args:
#   email or phone to use for delivery
login_id = "email@company.com"
#   delivery_method: support delivery methods - DeliveryMethod.SMS or DeliveryMethod.EMAIL
delivery_method = DeliveryMethod.EMAIL
#   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'
uri = "http://auth.company.com/api/verify_magiclink"
#   login_options (LoginOptions): this allows you to configure behavior during the authentication process.
login_options = {
      "stepup": false,
      "mfa": false,
      "custom_claims": {"claim": "Value1"},
      "template_options": {"option": "Value1"}
    }
#   refresh_token (optional): the user's current refresh token in the event of stepup/mfa

try:
  resp = descope_client.magiclink.sign_in(method=delivery_method, login_id=login_id, uri=uri, login_options=login_options)
  print ("Successfully initialized signin flow")
except AuthException as error:
  print ("Failed to initialize signin flow")
  print ("Status Code: " + str(error.status_code))
  print ("Error: " + str(error.error_message))
// Args:
//    ctx: context.Context - Application context for the transmission of context capabilities like
//        cancellation signals during the function call. In cases where context is absent, the context.Background()
//        function serves as a viable alternative.
//        Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
//    deliveryMethod: Delivery method to use to send magic link. Supported values include descope.MethodEmail or descope.MethodSMS
deliveryMethod := descope.MethodEmail
//    loginID: email or phone - the loginId for the user
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'
URI := "http://auth.company.com/api/verify_magiclink"
//    r: HttpRequest for the update call. This request should contain refresh token for the authenticated user.
//    loginOptions: this allows you to configure behavior during the authentication process.
loginOptions := &descope.LoginOptions{
    Stepup: true,
    MFA: true,
    CustomClaims: map[string]any{}{"test": "testClaim"},
    TemplateOptions: map[string]any{"option": "Value1"}
  }

err := descopeClient.Auth.MagicLink().SignIn(ctx, deliveryMethod, loginID, URI, r, loginOptions)
if (err != nil){
  fmt.Println("Failed to initialize signin flow: ", err)
} else {
  fmt.Println("Successfully initialized signin flow")
}
// If configured globally, the redirect URI is optional. If provided however, it will be used
// instead of any global configuration

// Every user must have a loginID. All other user information is optional
String loginId = "email@company.com";
User user = User.builder()
    .name("Joe Person")
    .phone("+15555555555")
    .email(loginId)
    .build();
var loginOptions = LoginOptions.builder()
				.stepUp(true)
        .mfa(true)
        .customClaims(
           new HashMap<String, Object>() {{
                put("custom-key1", "custom-value1");}}
        )
        .templateOptions(
           new HashMap<String, String>() {{
                put("option", "Value1");}}
        )
				.build();

MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();

try {
  String uri = "http://auth.company.com/api/verify_magiclink";
  var request = HttpRequest.newBuilder()
      .build();
  String maskedAddress = mls.signIn(DeliveryMethod.EMAIL, loginId, uri, request, loginOptions);

} catch (DescopeException de) {
  // Handle the 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 delivery_method to sms within the below example.

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

NodeJSPythonGoJava
// Args:
//    loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
const 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'
const uri = "http://auth.company.com/api/verify_magiclink"
//    deliveryMethod: Delivery method to use to send magic-link. Supported values include "email" or "sms"
const deliveryMethod = "email"
//    signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }

const resp = await descopeClient.magicLink.signUpOrIn[deliveryMethod](loginId, uri, signUpOptions);
if (!resp.ok) {
  console.log("Failed to initialize signUpOrIn flow")
  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 signUpOrIn flow")
}
# Args:
#   login_id: email or phone to use for delivery
login_id = "email@company.com"
#   delivery_method: support delivery methods - DeliveryMethod.SMS or DeliveryMethod.EMAIL
delivery_method = DeliveryMethod.EMAIL
#   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'
uri = "http://auth.company.com/api/verify_magiclink"
#   signup_options (SignUpOptions): this allows you to configure behavior during the authentication process.
signup_options = {
      "custom_claims": {"claim": "Value1"},
      "template_options": {"option": "Value1"}
    }

try:
  resp = descope_client.magiclink.sign_up_or_in(method=delivery_method, login_id=login_id, uri=uri, signup_options=signup_options)
  print ("Successfully initialized signup or in flow")
except AuthException as error:
  print ("Failed to initialize signup or in flow")
  print ("Status Code: " + str(error.status_code))
  print ("Error: " + str(error.error_message))
// Args:
//    ctx: context.Context - Application context for the transmission of context capabilities like
//        cancellation signals during the function call. In cases where context is absent, the context.Background()
//        function serves as a viable alternative.
//        Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
//    deliveryMethod: Delivery method to use to send magic link. Supported values include descope.MethodEmail or descope.MethodSMS
deliveryMethod := descope.MethodEmail
//    loginID: email or phone - the loginId for the user
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'
URI := "http://auth.company.com/api/verify_magiclink"
//    signUpOptions: this allows you to configure behavior during the authentication process.
signUpOptions := &descope.LoginOptions{
    Stepup: true,
    MFA: true,
    CustomClaims: map[string]any{}{"test": "testClaim"},
    TemplateOptions: map[string]any{"option": "Value1"}
  }

err := descopeClient.Auth.MagicLink().SignUpOrIn(ctx, deliveryMethod, loginID, URI, signUpOptions)
if (err != nil){
  fmt.Println("Failed to initialize signup or in flow: ", err)
} else {
  fmt.Println("Successfully initialized signup or in flow")
}
// If configured globally, the redirect URI is optional. If provided however, it will be used
// instead of any global configuration

// Every user must have a loginID. All other user information is optional
String loginId = "email@company.com";
User user = User.builder()
    .name("Joe Person")
    .phone("+15555555555")
    .email(loginId)
    .build();
var signUpOptions = SignupOptions.builder()
        .customClaims(
           new HashMap<String, Object>() {{
                put("custom-key1", "custom-value1");}}
        )
        .templateOptions(
           new HashMap<String, String>() {{
                put("option", "Value1");}}
        )
				.build();

MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();

try {
  String uri = "http://auth.company.com/api/verify_magiclink";
  String maskedAddress = mls.signUpOrIn(DeliveryMethod.EMAIL, loginId, uri, signUpOptions);

} catch (DescopeException de) {
  // Handle the 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.
NodeJSPythonGoJava
// Args:
//  token:  URL parameter containing the magic link token for example, https://auth.yourcompany.com/api/verify_magiclink?t=token.
const token = "xxxx"

const resp = await descopeClient.magicLink.verify(token)
if (!resp.ok) {
  console.log("Failed to verify magic link token")
  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 verified magic link token")
}
# Args:
#   token:  URL parameter containing the magic link token for example, https://auth.yourcompany.com/api/verify_magiclink?t=token.
token = "xxxx"

try:
    resp = descope_client.magiclink.verify(token=token)
    print ("Successfully verified user")
    print(json.dumps(resp, indent=4))
except AuthException as error:
    print ("Failed to verify user")
    print ("Status Code: " + str(error.status_code))
    print ("Error: " + str(error.error_message))
// Args:
//  ctx: context.Context - Application context for the transmission of context capabilities like
//        cancellation signals during the function call. In cases where context is absent, the context.Background()
//        function serves as a viable alternative.
//        Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
//  token:  URL parameter containing the magic link token for example, https://auth.yourcompany.com/api/verify_magiclink?t=token.
token := "xxxx"
//   w: ResponseWriter to update with correct session details. You can return this to your client for setting the cookies which are used for session validation

err := descopeClient.Auth.MagicLink().Verify(ctx, token, w)
if (err != nil){
  fmt.Println("Failed to verify user: ", err)
} else {
  fmt.Println("Successfully verified user")
}
MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();

try {
    AuthenticationInfo info = mls.verify(token);
} catch (DescopeException de) {
    // Handle the error
}

Update Email

This function allows you to update the user's email address via email. This requires a valid refresh token. Once the user has received the magic link, you will need to host a page to verify the magic link token using the magic link Verify Function.

NodeJSPythonGoJava
// Args:
//   loginId (str): The loginId of the user being updated
const loginId = "email@company.com"
//   email (str): The new email address. If an email address already exists for this end user, it will be overwritten
const email = "newEmail@company.com"
//   refreshToken (str): The session's refresh token (used for verification)
const refreshToken = "xxxxx"
//    updateOptions (UpdateOptions): this allows you to configure behavior during the authentication process.
const updateOptions = {
      "addToLoginIDs": true,
      "onMergeUseExisting": true,
      "templateOptions": {"option": "Value1"}
    }

const resp = await descopeClient.magiclink.update.email(loginId, email, refreshToken, updateOptions);
if (!resp.ok) {
  console.log("Failed to start magic link email update")
  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 started magic link email update")
  console.log(resp.data)
}
# Args:
#   login_id (str): The login_id of the user being updated
login_id = "email@company.com"
#   email (str): The new email address. If an email address already exists for this end user, it will be overwritten
email = "newEmail@company.com"
#   refresh_token (str): The session's refresh token (used for verification)
refresh_token = "xxxxx"
#   add_to_login_ids (boolean): if true, the email will be appended to the login ID array.
add_to_login_ids = True
#   on_merge_use_existing (boolean): if true, on merge, the existing user's information (roles, tenants, etc) will be retained
on_merge_use_existing = True
#   template_options (dict): email template options
template_options = {"option": "Value1"}

try:
    jwt_response = descope_client.magiclink.update_user_email(login_id=login_id, email=email, refresh_token=refresh_token, add_to_login_ids=add_to_login_ids, on_merge_use_existing=on_merge_use_existing, template_options=template_options)
    print ("Successfully started magic link email update")
    print(json.dumps(jwt_response, indent=4))
except AuthException as error:
    print ("Failed to start magic link email update")
    print ("Status Code: " + str(error.status_code))
    print ("Error: " + str(error.error_message))
// Args:
//   ctx: context.Context - Application context for the transmission of context capabilities like
//        cancellation signals during the function call. In cases where context is absent, the context.Background()
//        function serves as a viable alternative.
//        Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
//   loginId (str): The loginId of the user being updated
loginID := "email@company.com"
//   email (str): The new email address. If an email address already exists for this end user, it will be overwritten
email := "newEmail@company.com"
//   updateOptions (&descope.UpdateOptions): this allows you to configure behavior during the authentication process.
updateOptions := &descope.UpdateOptions{}
updateOptions.AddToLoginIDs = false
updateOptions.OnMergeUseExisting = false
updateOptions.TemplateOptions = map[string]any{"option": "Value1"}
//   request (*http.Request): Request is needed to obtain JWT and send it to Descope, for verificatio


res, err := descopeClient.Auth.MagicLink().UpdateUserEmail(ctx, loginID, email, updateOptions, request)
if (err != nil){
  fmt.Println("Failed to start magic link email update: ", err)
} else {
  fmt.Println("Successfully started magic link email update", res)
}
// Will throw DescopeException if there is an error with update
MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();

try {
  AuthenticationInfo info = mls.updateUserEmail(loginId, email, refreshToken, UpdateOptions);
} catch (DescopeException de) {
  // Handle the error
}

Update Phone

This function allows you to update the user's phone number address via SMS. This requires a valid refresh token. Once the user has received the magic link Code, you will need to host a page to verify the magic link code using the magic link Verify Function.

NodeJSPythonGoJava
// Args:
//   deliveryMethod: Delivery method to use to send magic link.
const deliveryMethod = "sms"
//   loginId (str): The loginId of the user being updated
const loginId = "phone@company.com"
//   phone (str): The new phone number. If a phone number already exists for this end user, it will be overwritten
const phone = "+12223334455"
//   refreshToken (str): The session's refresh token (used for verification)
const refreshToken = "xxxxx"
//    updateOptions (UpdateOptions): this allows you to configure behavior during the authentication process.
const updateOptions = {
      "addToLoginIDs": true,
      "onMergeUseExisting": true,
      "templateOptions": {"option": "Value1"}
    }

const resp = await descopeClient.magiclink.update.phone(deliveryMethod, loginId, phone, refreshToken, updateOptions);
if (!resp.ok) {
  console.log("Failed to start magic link phone update")
  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 started magic link phone update")
  console.log(resp.data)
}
# Args:
#   delivery_method: Method used to deliver the magic link.
delivery_method = DeliveryMethod.SMS
#   login_id (str): The login_id of the user being updated
login_id = "phone@company.com"
#   phone (str): The new phone number. If a phone number already exists for this end user, it will be overwritten
phone = "+12223334455"
#   refresh_token (str): The session's refresh token (used for verification)
refresh_token = "xxxxx"
#   add_to_login_ids (boolean): if true, the phone will be appended to the login ID array.
add_to_login_ids = True
#   on_merge_use_existing (boolean): if true, on merge, the existing user's information (roles, tenants, etc) will be retained
on_merge_use_existing = True
#   template_options (dict): email template options
template_options = {"option": "Value1"}

try:
    jwt_response = descope_client.magiclink.update_user_phone(delivery_method=delivery_method, login_id=login_id, phone=phone, refresh_token=refresh_token, add_to_login_ids=add_to_login_ids, on_merge_use_existing=on_merge_use_existing, template_options=template_options)
    print ("Successfully started magic link phone update")
    print(json.dumps(jwt_response, indent=4))
except AuthException as error:
    print ("Failed to start magic link phone update")
    print ("Status Code: " + str(error.status_code))
    print ("Error: " + str(error.error_message))
// Args:
//   ctx: context.Context - Application context for the transmission of context capabilities like
//        cancellation signals during the function call. In cases where context is absent, the context.Background()
//        function serves as a viable alternative.
//        Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
//   deliveryMethod: Method used to deliver the magic link.
deliveryMethod := descope.MethodSMS
//   loginId (str): The loginId of the user being updated
loginID := "phone@company.com"
//   phone (str): The new phone number. If a phone number already exists for this end user, it will be overwritten
phone := "+12223334455"
//   updateOptions (&descope.UpdateOptions): this allows you to configure behavior during the authentication process.
updateOptions := &descope.UpdateOptions{}
updateOptions.AddToLoginIDs = false
updateOptions.OnMergeUseExisting = false
updateOptions.TemplateOptions = map[string]any{"option": "Value1"}
//   request (*http.Request): Request is needed to obtain JWT and send it to Descope, for verificatio


res, err := descopeClient.Auth.MagicLink().UpdateUserPhone(ctx, deliveryMethod, loginID, phone, updateOptions, request)
if (err != nil){
  fmt.Println("Failed to start magic link phone update: ", err)
} else {
  fmt.Println("Successfully started magic link phone update", res)
}
// Will throw DescopeException if there is an error with update
MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();

try {
  AuthenticationInfo info = mls.updateUserPhone(deliveryMethod, loginId, phone, refreshToken, UpdateOptions);
} catch (DescopeException de) {
  // Handle the 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 backend session validation here.



left parenthesis
Checkpoint: Your application is now integrated with Descope. Please test with sign-up or sign-in use case.
right parenthesis