Add SMS OTP Login


# Add SMS OTP Login

SMS OTP (One-Time Password) is a security mechanism where a password, valid for a short duration, is sent to the user's registered mobile number. This password must be entered during the login process.

This method can be used as a form of passwordless authentication, allowing users to log in by providing a one-time passcode received via SMS on their mobile phones, instead of using a traditional password.

To configure SMS OTP as a passwordless authentication mechanism in Asgardeo, follow the instructions given below.

# Prerequisites

# Set up SMS OTP

To enable SMS OTP for the organization:

  1. On the Asgardeo Console (opens new window), go to Connections and select SMS OTP.

  2. Update the following parameters in the Settings tab:

    Setup SMS OTP in Asgardeo
    SMS OTP expiry time The generated OTP will not be valid after this expiry time.
    Use only numeric characters for OTP If this checkbox is checked, the generated OTP will only contain digits (0-9). If the checkbox is unchecked, the OTP will contain alphanumeric characters.
    SMS OTP length Specifies the number of characters allowed in the OTP.
  3. Click update to save your configurations.

# Configuring SMS Providers

Configurations related to SMS providers are located under the Email & SMS section.

# Supported Providers

Asgardeo supports Twilio, Vonage, or custom SMS providers by default. To learn how to configure each provider, please see the relevant section.

Configuring Twilio

To configure Twilio as your SMS provider, follow the steps below:

  • Go to Twilio (opens new window) and create an account.
  • After signing up for your account, navigate to the Phone Numbers page in your console. You’ll see the phone number that has been selected for you. Note the phone number’s capabilities, such as "Voice", "SMS", and "MMS".
  • After signing up, navigate to the Phone Numbers page in your console and note the phone number’s capabilities.
  • Get your first Twilio phone number and use that as the “Sender” in the settings. For more information, see this tutorial in the Twilio documentation.
  • Copy the Account SID and Auth Token from the Twilio console dashboard.
  • Go to SMS Provider section in the Console and click the Twilio tab and fill the required fields.
Name Description Example
Twilio Account SID Account SID received in the previous step. YourAccountSID
Twilio Auth Token Auth token received in the previous step. YourAuthToken
Sender Phone number that you received when creating the Twilio account. +1234567890
Configuring Vonage

To configure Vonage as your SMS provider, follow the steps below:

  • Login to Vonage (opens new window) and create an account.
  • Fill in the required fields and create the account.
  • Login to the Vonage dashboard and copy the API Key and API Secret.
  • Go to SMS Provider section in the Console and click the Vonage tab and fill the required fields.
Name Description Example
Vonage API Key Use the API Key from the previous step. YourAPIKey
Vonage API Secret Use the API Secret from the previous step. YourAPISecret
Sender The number that the receiver will see when you send an SMS. +1234567890
Configuring a Custom Provider

If you are not using either Twilio or Vonage as the SMS provider, you can configure a custom SMS provider. Custom SMS provider configuration will pass the SMS data to the given URL as an HTTP request.

To configure a custom SMS provider, in the SMS Provider section click the Custom tab and fill the required fields.

Name Description Example
SMS Provider URL URL of the SMS gateway where the payload should be published. https://api.example.com/api/v1
Content Type Content type of the payload. Possible values are JSON or FORM (Optional). JSON
HTTP Method HTTP method that should be used when publishing the payload to the provider URL. Possible values: PUT, POST (Optional). POST
Payload Template How the payload template should be.
Placeholders:
{{body}} - Generated body of the SMS. (Example - This can be the OTP).
{{mobile}} - Number that this sms should be sent to.
Example JSON payload template:
{“content”: {{body}},“to”: {{mobile}}}}

({{mobile}} and {{body}} will be replaced with the corresponding values at the runtime.)
Headers Custom static headers need to be passed. If multiple headers need to be passed, they should be comma separated. (Optional) authorisation: qwer1234asdfzxcv, x-csrf: true, x-abc: some-value

# Implement business logic for SMS OTP notification events

Asgardeo's SMS OTP authenticator publishes notification data events. You can create a webhook in Choreo (opens new window), WSO2's integration platform, to subscribe to these events and execute custom business logic, such as to send an SMS via an SMS gateway.

# Define the business logic

Follow the steps below to programmatically define the business logic to send an SMS OTP via an SMS gateway whenever a notification event occurs.

Prerequisites

  • You need to have a Github repository to host the business logic.

  • Download Ballerina (opens new window), the programming language used to define business logic for Asgardeo events.

  1. Create a new Ballerina package. Learn how to do so in the Ballerina documentation (opens new window).

  2. Navigate to the Ballerina.toml file and rename the organization name to that of your Asgardeo organization.

  3. Navigate to your main.bal file and define the business logic.

    New to Ballerina?

    Learn more about the Asgardeo trigger module and how to program business logic for SMS OTP notification data events in the Ballerina documentation (opens new window).

    The following sample logic logs the notification event in the Choreo console and sends an SMS Message via an SMS Gateway.

    import ballerinax/trigger.asgardeo;
    import ballerina/http;
    import ballerina/log;
    import wso2/choreo.sendsms;
    
    configurable asgardeo:ListenerConfig config = ?;
    
    listener http:Listener httpListener = new(8090);
    listener asgardeo:Listener webhookListener =  new(config,httpListener);
    
    sendsms:Client sendSmsClient = check new ();
    
    service asgardeo:NotificationService on webhookListener {
        
        remote function onSmsOtp(asgardeo:SmsOtpNotificationEvent event) returns error? {
          
          //logging the event.
          log:printInfo(event.toJsonString());
    
          //read required data from the event.
          asgardeo:SmsOtpNotificationData? eventData = event.eventData;
          string toNumber = <string> check eventData.toJson().sendTo;
          string message = <string> check eventData.toJson().messageBody;
    
          string response = check sendSmsClient -> sendSms(toNumber, message);
          log:printInfo(response);
        } 
    }
    
    service /ignore on httpListener {}
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    SmsOtpNotificationEvent Metadata

    The payload of the SmsOtpNotificationEvent contains the following metadata:

    • Security Data object: The security data object is the same as all other Asgardeo events (opens new window). This contains the following security metadata about the event.

      Property Name Type Description
      iss String Issuer of the event
      iat String Event published timestamp.
      jti String Unique identifier for the event.
      aud String Audience of the event.

      Sample security data object:

      {
        "iss": "Asgardeo",
        "jti": "3b69b103-fa6c-424a-bbf4-a974d0c2d2a3",
        "iat": 1659732032884,
        "aud": "https://websubhub/topics/myorg/NOTIFICATIONS"
      }
      
      1
      2
      3
      4
      5
      6
    • Event Data object - The event data object contains the details of the event. This contains the following metadata about the notification event.

      Property Name Type Description
      organizationId int Organization Identifier
      organizationName String Organization name
      sendTo String Mobile number receiving the SMS OTP.
      messageBody String Content of the SMS OTP Message

      Sample event data object:

      {
        "organizationId": 3,
        "organizationName": "myorg",
        "sendTo": "+1234567890"
        "messageBody": "Your one-time password for the myapp is 075052. This expires in 5 minutes.",
      }
      
      1
      2
      3
      4
      5
      6
  4. Commit your changes and push the code to your remote Github repository.

# Create a webhook in Choreo

Follow the steps below to create and deploy a webhook in Choreo.

  1. Navigate to Choreo (opens new window) and if you don't have one already, create an organization with the same name and email address you used to create your Asgardeo organization.

    Organizations in Asgardeo and Choreo synchronize based on their names.

  2. Select a project from the Project dropdown.

  3. Go to Components, and click Create.

  4. Under the Select a Type tab, select Webhook. Learn more about webhooks in the Choreo documentation (opens new window).

    Create a Webhook in Choreo
  5. Enter a name and a description for your webhook.

  6. Click Authorize with Github and connect the relevant organization, repository and the branch of the Github repository you created in the above section.

  7. Select Ballerina to be the Buildpack and select the Ballerina Project Directory from your Github repository.

  8. Select the Access Mode as External and click Create.

    Connect Github repository to Choreo
  9. Follow the Choreo documentation and deploy your webhook (opens new window).

# Enable SMS OTP login for an app

Follow the steps given below to enable SMS OTP login to the login flow of your application.

  1. On the Asgardeo Console, use one of the following options to start:

    • Option 1: Go to Applications.
    • Option 2: Go to Connections > Passwordless and for the SMS OTP connection, click Set up.
  2. Select the application for which SMS OTP login needs to be enabled.

  3. Go to the Login Flow tab of the application and add SMS OTP login from your preferred editor:

    Using the Classic Editor
    • If you haven’t already built a login flow for your application, select Add SMS OTP login to build one.

      Configuring SMS OTP login in Asgardeo
    • If you have an already built login flow, add the SMS OTP authenticator as the first authentication step.

      Customize the login flow
    Using the Visual Editor

    To add passwordless login with SMS OTP using the Visual Editor:

    1. Switch to the Visual Editor tab and go to Predefined Flows > Basic Flows > Add Passwordless login.

    2. Select SMS OTP.

    3. Click Confirm to add passwordless login with SMS OTP to the sign-in flow. Configuring SMS OTP login in Asgardeo using the Visual Editor

  4. Click Update to save your changes.

# Try it out

Follow the steps given below.

  1. Access the application URL.
  2. Click Login to open the Asgardeo login page.
  3. On the Asgardeo login page, enter your username and press Continue. Sign In with SMS OTP in Asgardeo You will be redirected to the below SMS OTP page. SMS OTP submit page
  4. Check your phone for the SMS containing the one-time passcode.
  5. Enter the received passcode on the SMS OTP page and click Continue.