Two-Factor Authentication Using .NET

    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 Dotnet Dev Environment

    You must set up and install Dotnet Framework(.NET Framework 4.6 or higher) and Plivo’s Dotnet SDK to implement send SMS use-case. Here’s how.

    Install Dotnet Framework

    Operating SystemInstructions
    macOS & LinuxYou would already have Dotnet Framework installed, you can check this by running the command dotnet --version in the terminal. If you do not have it installed, you can install it from here.
    WindowsTo install Dotnet Framework on Windows you can follow the instructions from here.

    Set Up the Demo app locally

    • Clone the repository from Github
     $ git clone https://github.com/plivo/2fa-dotnet-demo.git
    • Change your working directory to 2fa-dotnet-demo
     $ cd 2fa-dotnet-demo
    • Open the 2fa folder in Visual Studio.
    • Install the Plivo Nuget package Install Plivo Nuget Package
    • Change the placeholders in the appsettings.json 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 Dotnet.

    1
    2
    
    Random r = new Random();
    var code = r.Next(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
    14
    15
    16
    17
    18
    
    public int SendVerificationCodePhlo(String DstNumber, String mode)
    		{
    			Random r = new Random();
    			var code = r.Next(999999);
                var phloClient = new PhloApi(AuthId, AuthToken);
                var phloID = PhloId;
                var phlo = phloClient.Phlo.Get(phloID); 
                var data = new Dictionary<string, object>
                {
                    { "from", AppNumber },
                    { "to", DstNumber },
    				{ "mode", mode },
    				{ "otp", code },
    
                };  
    			phlo.Run(data);
                return code;
    		}
    

    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 Dotnet.

    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
    31
    32
    33
    34
    35
    36
    
    public string Index(string number, string code)
    		{
    			ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(_configuration.GetValue<string>("RedisHost"));
    			IDatabase conn = redis.GetDatabase();
    
    			string key = $"number:{number}:code";
    			var compare_code = (string)conn.StringGet(key);
    
    			
    				if (compare_code == code)
    				{
    					conn.KeyDelete(key);
    					Verification verification = new Verification();
    					verification.status = "success";
                        verification.message = "Number verified";
    					string output = JsonConvert.SerializeObject(verification);
    					return output;
    				}
    				else if(compare_code != code)
    				{
    					Verification verification = new Verification();
    					verification.status = "failure";
    					verification.message = "Number verified";
    					string output = JsonConvert.SerializeObject(verification);
    					return output;
    				}
    			
    				else
    				{
    					Verification verification = new Verification();
    					verification.status = "failure";
    					verification.message = "number not found!";
    					string output = JsonConvert.SerializeObject(verification);
    					return output;
    				}
    		}
    

    Test and Validate

    Build and Run the app from Visual Studio and you check the app in action on http://localhost:5001/ or https://3b3e783f.ngrok.io/ Dotnet Run

    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 Dotnet Dev Environment

    You must set up and install Dotnet Framework(.NET Framework 4.6 or higher) and Plivo’s Dotnet SDK to implement the use-case. Here’s how.

    Install Dotnet Framework

    Operating SystemInstructions
    macOS & LinuxYou would already have Dotnet Framework installed, you can check this by running the command dotnet --version in the terminal. If you do not have it installed, you can install it from here.
    WindowsTo install Dotnet Framework on Windows you can follow the instructions from here.

    Set Up the Demo app locally

    • Clone the repository from Github
     $ git clone https://github.com/plivo/2fa-dotnet-demo.git
    • Change your working directory to 2fa-dotnet-demo
     $ cd 2fa-dotnet-demo
    • Open the 2fa folder in Visual Studio.
    • Install the Plivo Nuget package Install Plivo Nuget Package
    • Change the placeholders in the appsettings.json 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 Dotnet.

    1
    2
    
    Random r = new Random();
    var code = r.Next(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
    
    public int SendVerificationCodeSms(String DstNumber, String Message)
    		{
    			Random r = new Random();
    			var code = r.Next(999999);
                var response = Client.Message.Create(
                    src: AppNumber,
                    dst: new List<String> { DstNumber },
                    text: Message.Replace("__code__", code.ToString()));
                return code;
    		}
    

    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 Dotnet.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    public int SendVerificationCodeCall(String DstNumber)
    		{
    			Random r = new Random();
    			var code = r.Next(999999);
                var response = Client.Call.Create(
                    to:new List<String>{DstNumber},
                        from:AppNumber,
                        answerMethod:"POST",
                        answerUrl:"https://twofa-answerurl.herokuapp.com/answer_url/"+code);
                return code;
    		}
    

    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 Dotnet.

    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
    31
    32
    33
    34
    35
    36
    
    public string Index(string number, string code)
    		{
    			ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(_configuration.GetValue<string>("RedisHost"));
    			IDatabase conn = redis.GetDatabase();
    
    			string key = $"number:{number}:code";
    			var compare_code = (string)conn.StringGet(key);
    
    			
    				if (compare_code == code)
    				{
    					conn.KeyDelete(key);
    					Verification verification = new Verification();
    					verification.status = "success";
                        verification.message = "Number verified";
    					string output = JsonConvert.SerializeObject(verification);
    					return output;
    				}
    				else if(compare_code != code)
    				{
    					Verification verification = new Verification();
    					verification.status = "failure";
    					verification.message = "Number verified";
    					string output = JsonConvert.SerializeObject(verification);
    					return output;
    				}
    			
    				else
    				{
    					Verification verification = new Verification();
    					verification.status = "failure";
    					verification.message = "number not found!";
    					string output = JsonConvert.SerializeObject(verification);
    					return output;
    				}
    		}
    

    Test and Validate

    Build and Run the app from Visual Studio and you check the app in action on http://localhost:5001/ or https://3b3e783f.ngrok.io/ Dotnet Run

    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.