Two-factor authentication using PHP

    Two-factor authentication (2FA) can play a key role in securing your applications against password data breaches. Authentication with a one-time password (OTP) delivered to your users over SMS is an effective approach to implementing two-factor authentication. Plivo’s premium direct routes guarantee the highest possible delivery rates and the shortest possible delivery times for your 2FA SMS messages.

    This guide shows how to set up SMS-based two-factor authentication using either PHLO or traditional API development. PHLO lets you create and deploy workflows from an intuitive graphical canvas in few clicks.

    To implement Two-factor use case, you can create and deploy a PHLO with a few clicks on the PHLO canvas. PHLO also lets you visually construct your entire use-case. With PHLO, you only pay for SMS you send/receive, and building with PHLO is free.

    Implementation

    In this section, we will guide you to create a PHLO to implement Two-factor use-case.

    Prerequisites

    • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo Console. Click here to sign-up for a Plivo account if you haven’t already!

      Find Your Auth Credentials on Plivo Console

    • Plivo Phone Number(Optional): To send messages to the United States and Canada, you must have a Plivo phone number that supports SMS. Numbers can be purchased from the Numbers section of your Plivo Console and use the same as the source number/from number for the outbound SMS. This number will also help you receive incoming SMS as you must have a SMS-enabled Plivo phone number to do the same. Please note that you can also purchase numbers using the Numbers API.

      Buy a New Plivo Number

    • Github account(Optional): To get the code from the repository, clone it. Otherwise, since the repository is open to the public, we can download the code and run it locally.

    Create the PHLO

    With PHLO, you can quickly create a workflow that suits your use case. To use PHLO, make sure to register and log on to Plivo Console. There is already a prototype for this use-case; all you need to do is select the PHLO and give it a friendly name.

    PHLO Setup

    Set up Your PHP Dev Environment

    You must set up and install PHP and Plivo’s PHP SDK to make a bulk call. Here’s how.

    Install PHP

    Operating SystemInstructions
    macOSYou can install PHP using the official installer. You can also install it from here.
    LinuxTo install PHP on Linux you can find the instructions here.
    WindowsTo instll PHP on Windows you can use the official installer.

    Install Composer

    Composer is a dependency manager for PHP that is used in all modern PHP frameworks, such as Symfony and Laravel. We highly recommend using Composer as the package manager for your web project.

    1. Download the latest version of Composer.
    2. Run the following command in Terminal in order to run the composer:

       $ php ~/Downloads/composer.phar --version
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make it executable:

       $ cp ~/Downloads/composer.phar /usr/local/bin/composer
       $ sudo chmod +x /usr/local/bin/composer
       $ Make sure you move the file to bin directory.
      
    4. To check if the path has /usr/local/bin, use

       $ echo $PATH
      

      If the path is different, use the following command to update the $PATH:

       $ export PATH = $PATH:/usr/local/bin
       $ source ~/.bash_profile
      

      Note: If your PATH doesn’t include /usr/local/bin directory, we recommend adding it so that you can access it globally.

    5. You can also check the version of Composer by running the following command:

       $ composer --version.       
      

    1. Run the following command:

       $ curl -sS https://getcomposer.org/installer | php
      
    2. Run the following command to make the composer.phar file as executable:

       $ chmod +x composer.phar
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make Composer globally available for all system users:

       $ mv composer.phar /usr/local/bin/composer
      

    1. Download and run the Windows Installer for Composer.

      Note: Make sure to allow Windows Installer for Composer to make changes to your php.ini file.

    2. If you have any terminal windows open, close all instances and open a fresh terminal instance.
    3. Run the Composer command.

       $ composer -V
      

    Set Up the Demo app locally

    • Clone the repository from Github
     $ git clone https://github.com/plivo/2fa-php-demo.git
    • Change your working directory to 2fa-php-demo
     $ cd 2fa-php-demo
    • Install the dependencies using the composer.json file. You can use the below command.
     $ composer install
    • Change the placeholders in the config.ini file. You should replace the PLIVO_AUTH_ID, PLIVO_AUTH_TOKEN,PLIVO_NUMBER & PHLO_ID placeholders. Configuration file
    Note: Enter your phone number in E.164 format.
    • Turn on the redis server by entering the following command in your terminal
     $ redis-server

    Redis Server

    • The different steps that are involved in this app are as follows:

    Step 1 : Generate the OTP

    Generate an exclusive six-digit authentication code (OTP). To create the OTP, we will use the Time Based OTP generation algorithm. here’s how it’s done in PHP.

    1
    
    $code = rand(100000, 999999);
    

    Step 2 : Send SMS & Make a call

    A single function help us to trigger to Send SMS and Make call via PHLO and the rest is done by the PHLO in your console. The main argument which tells PHLO to trigger call or an SMS is mode the values passed within are sms & call.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    function send_verification_code_phlo($dst_number,$mode)
        {
            $code = rand(100000, 999999);
            $client = new PhloRestClient($this->config['auth_id'], $this->config['auth_token']);
            try {
                $phlo = $client->phlo->get($this->config['phlo_id']);
                $phlo->run(["from" => $this->config['app_number'], "to" => $dst_number, "mode"=>$mode, "otp"=>$code]); // These are the fields entered in the PHLO console
                return $code;
            } 
            catch (PlivoRestException $ex) {
                print_r($ex);
            }
        }
    

    Step 3 : Verify the OTP

    Once the user enters the OTP received to their handset, the code will be verified and here’s how it’s done in PHP.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    <?php
    /**
     * Initiate Validation process
     * @param $param[2] route param(Phone number) from index.php
     * @param $param[3] route param(OTP entered by user) from index.php
     */
    $number = $param[2];
    $code   = $param[3];
    
    $original_code = $client->get('number:' . $number . ':code');
    
    if ($original_code == $code) {
        $client->del('number:' . $number . ':code');
        echo '{"status": "success", "message": "codes match! number verified"}';
    } elseif ($original_code != $code) {
        echo '{"status": "failure", "message": "codes do not match! number not verified"}';
    } else {
        echo '{"status": "failure", "message": "number not found!"}';
    }
    ?>
    

    Test and Validate

    In order to run the app, run the following command.

    $ php -S localhost:8000
    

    You check the app in action on https://3b3e783f.ngrok.io/

    The finished app should look like this. Two-Factor Authentication

    Note: If you are using a Plivo Trial account for this example, you can only send SMS to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

    To implement two Factor Authentication use-case in the traditional API way, you can refer to the instructions in the below section to begin your implementation.

    Implementation

    In this section, we will guide you in setting up an app using Plivo’s API to implement two factor authentication. First, let’s make sure you meet these prerequisites before we dive into the code.

    Prerequisites

    • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo Console. Click here to sign-up for a Plivo account if you haven’t already!

      Find Your Auth Credentials on Plivo Console

    • Plivo Phone Number(Optional): To send messages to the United States and Canada, you must have a Plivo phone number that supports SMS. Numbers can be purchased from the Numbers section of your Plivo Console and use the same as the source number/from number for the outbound SMS. This number will also help you receive incoming SMS as you must have a SMS-enabled Plivo phone number to do the same. Please note that you can also purchase numbers using the Numbers API.

      Buy a New Plivo Number

    • Github account(Optional): To get the code from the repository, clone it. Otherwise, since the repository is open to the public, we can download the code and run it locally.

    Set up Your PHP Dev Environment

    You must set up and install PHP and Plivo’s PHP SDK to implement Two-factor authentocation. Here’s how.

    Install PHP

    Operating SystemInstructions
    macOSYou can install PHP using the official installer. You can also install it from here.
    LinuxTo install PHP on Linux you can find the instructions here.
    WindowsTo instll PHP on Windows you can use the official installer.

    Install Composer

    Composer is a dependency manager for PHP that is used in all modern PHP frameworks, such as Symfony and Laravel. We highly recommend using Composer as the package manager for your web project.

    1. Download the latest version of Composer.
    2. Run the following command in Terminal in order to run the composer:

       $ php ~/Downloads/composer.phar --version
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make it executable:

       $ cp ~/Downloads/composer.phar /usr/local/bin/composer
       $ sudo chmod +x /usr/local/bin/composer
       $ Make sure you move the file to bin directory.
      
    4. To check if the path has /usr/local/bin, use

       $ echo $PATH
      

      If the path is different, use the following command to update the $PATH:

       $ export PATH = $PATH:/usr/local/bin
       $ source ~/.bash_profile
      

      Note: If your PATH doesn’t include /usr/local/bin directory, we recommend adding it so that you can access it globally.

    5. You can also check the version of Composer by running the following command:

       $ composer --version.       
      

    1. Run the following command:

       $ curl -sS https://getcomposer.org/installer | php
      
    2. Run the following command to make the composer.phar file as executable:

       $ chmod +x composer.phar
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make Composer globally available for all system users:

       $ mv composer.phar /usr/local/bin/composer
      

    1. Download and run the Windows Installer for Composer.

      Note: Make sure to allow Windows Installer for Composer to make changes to your php.ini file.

    2. If you have any terminal windows open, close all instances and open a fresh terminal instance.
    3. Run the Composer command.

       $ composer -V
      

    Set Up the Demo app locally

    • Clone the repository from Github
     $ git clone https://github.com/plivo/2fa-php-demo.git
    • Change your working directory to 2fa-php-demo
     $ cd 2fa-php-demo
    • Install the dependencies using the composer.json file. You can use the below command.
     $ composer install
    • Change the placeholders in the config.ini file. You should replace the PLIVO_AUTH_ID, PLIVO_AUTH_TOKEN & PLIVO_NUMBER placeholders. Configuration file
  • Note: Enter your phone number in E.164 format.
  • Note: In case if you wouldn't like to you use PHLO then update the value as PHLO_ID = null.
    • Turn on the redis server by entering the following command in your terminal
     $ redis-server

    Redis Server

    • The different steps that are involved in this app are as follows:

    Step 1 : Generate the OTP

    Generate an exclusive six-digit authentication code (OTP). To create the OTP, we will use the Time Based OTP generation algorithm. here’s how it’s done in PHP.

    1
    
    $code = rand(100000, 999999);
    

    Step 2 : Send SMS message with OTP

    Send SMS with OTP to the user’s registered mobile number using Plivo’s Send Message API.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    function send_verification_code_sms($dst_number, $message)
        {
            $code = rand(100000, 999999);
            try{
                $this->$client->messages->create($this->config['app_number'], [$dst_number], str_replace("__code__", $code, $message));
                return $code;
    
            }
            catch (PlivoRestException $ex) {
                print_r($ex);
            }
            
        }
    

    Step 3 : Make a phone call with OTP(Failover)

    When messages aren’t deliverable for a variety of reasons, the user can choose voice OTP, and here’s how it’s done in PHP.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    function send_verification_code_call($dst_number)
        {
            $code = rand(100000, 999999);
            try 
            {
                $this->$client->calls->create($this->config['app_number'], [$dst_number], 'https://twofa-answerurl.herokuapp.com/answer_url/'.$code,'POST');
                return $code;
            }
            catch (PlivoRestException $ex) {
                print_r($ex);
            }
        }
    

    Step 4 : Verify the OTP

    Once the user enters the OTP received to their handset, the code will be verified and here’s how it’s done in PHP.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    <?php
    /**
     * Initiate Validation process
     * @param $param[2] route param(Phone number) from index.php
     * @param $param[3] route param(OTP entered by user) from index.php
     */
    $number = $param[2];
    $code   = $param[3];
    
    $original_code = $client->get('number:' . $number . ':code');
    
    if ($original_code == $code) {
        $client->del('number:' . $number . ':code');
        echo '{"status": "success", "message": "codes match! number verified"}';
    } elseif ($original_code != $code) {
        echo '{"status": "failure", "message": "codes do not match! number not verified"}';
    } else {
        echo '{"status": "failure", "message": "number not found!"}';
    }
    ?>
    

    Test and Validate

    In order to run the app, run the following command.

    $ php -S localhost:8000
    

    You check the app in action on https://3b3e783f.ngrok.io/

    The finished app should look like this. Two-Factor Authentication

    Note: If you are using a Plivo Trial account for this example, you can only send SMS to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.