Generate One Time Password (OTP) in Asp.Net using C#.Net

In this asp.net tutorial, I will explain with an example, how to generate Unique Random OTP i.e. One Time Password in Asp.Net using C#.Net.

One Time Passwords are widely used by banks and other firms to validate the Mobile Numbers of their users. OTPs can be Alphanumeric or Numeric and generally have a length between 5-10 characters.

My application is basically a login screen which uses username and password. Next, it will validate with the server to check a valid user or not. Once it validates with success result, next it will generate an OTP which will send to your register mobile no. The OTP last 5 minutes, after this time, it will expire and the user will need to generate a new one. 

Now I am going to explain to make easier your comprehension. First I start with a screenshot of my application.

Step 1: Open your Visual Studio next create a new solution.

generate otp asp.net
generate otp asp.net

Step 2: First I am going to create a simple login screen which will valid a registered user or not in my application.

generate otp asp.net using c#.net
generate otp asp.net using c#.net

Step 3: In this step, it will validate the credential if it will success then it will redirect to OTP page where you can see your registered mobile no which can help you to send an OTP.

generate one time password otp asp.net
generate one time password otp asp.net

Step 4: Next it will generate an OTP and same time OTP will send to your registered mobile no and the validity is only for 5 minutes after that it does not work.

generate one time password otp asp.net using c#.net
generate one time password otp asp.net using c#.net

Step 4: If you will enter the correct OTP, then you can able to see the next page otherwise you will receive an alert ( Invalid OTP ).

Note: One point should be noted. Here I am using cookies to save the user credential because, If the same user wants to log in this application in the second time in the same day with the same browser then it won’t ask for OTP as this user has already logged in to the site for the same day.

If the user will log in to the site in a different browser or different system then only it will ask you for OTP. The validity of the cookies is only for 24 hours after that it will delete automatically from your browser.

Step 5: Here is the simple code to generate OTP .

how to generate otp asp.net
how to generate otp asp.net

Step 6: Make sure you have created two tables in your database. The name of the database is OTPdb and here I have created two tables called Login_Check_SP and OTPhistortbl.

In Login_Check_Sp table: It will validate the authenticate user and OTPhistortbl is used to keep all OTP generation history of the user.

how to generate otp asp.net using c#.net
how to generate otp asp.net using c#.net

Step 7: When your database gets created, next connect to your database through connection string which you have to set in web.config file.

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>
  <connectionStrings>
    <add name="conStr" connectionString="Data Source=WIN-EGHTVPHQ2VT;Initial Catalog=OTPdb;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Step 8: Here is the HTML code for the Login screen and generate OTP.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"/>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>


    <style type="text/css">
        @import url(https://fonts.googleapis.com/css?family=Exo:400,500,500italic,400italic,600,600italic,700,700italic,800,800italic,300,300italic);

        body {
  padding-top: 250px;
	/*The below background is just to add some color, you can set this to anything*/
  background: url(http://www.magic4walls.com/wp-content/uploads/2014/01/texture-blue-fonchik-simple-dark-colors-glow-background.jpg) no-repeat;
}

.login-form{width:390px;}
.login-title{font-family: 'Exo', sans-serif;text-align:center;color: white;}
.login-userinput{margin-bottom: 10px;}
.login-button{margin-top:10px;}
.login-options{margin-bottom:0px;}
.login-forgot{float: right;}
    </style>
<script type="text/javascript">
    window.onload = function () { $("#showPassword").hide(); }

    $("#txtPassword").on('change', function () {
        if ($("#txtPassword").val()) {
            $("#showPassword").show();
        }
        else {
            $("#showPassword").hide();
        }
    });

    $(".reveal").on('click', function () {
        var $pwd = $("#txtPassword");
        if ($pwd.attr('type') === 'password') {
            $pwd.attr('type', 'text');
        }
        else {
            $pwd.attr('type', 'password');
        }
    });
</script>

    <title>
        Send OTP
    </title>

    </head>
<body>
   <form runat="server">
       <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div class="container login-form">
	<h2 class="login-title">- Please Login -</h2>
	<div class="panel panel-default">

		<div class="panel-body">
		
				<div class="input-group login-userinput">
					<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
                    <asp:TextBox ID="txtUser" class="form-control" runat="server" placeholder="Username"></asp:TextBox>
				</div>
				<div class="input-group">
					<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
                     <asp:TextBox ID="txtPassword" runat="server" class="form-control" name="password" placeholder="Password"></asp:TextBox>
					<span id="showPassword" class="input-group-btn">
            <button class="btn btn-default reveal" type="button"><i class="glyphicon glyphicon-eye-open"></i></button>
          </span>  
				</div>				
                <asp:Button ID="Btnsubmit" class="btn btn-primary btn-block login-button" runat="server" Text="Login" OnClick="Btnsubmit_Click" />
				<div class="checkbox login-options">
					<label><input type="checkbox"/> Remember Me</label>
					<a href="#" class="login-forgot">Forgot Username/Passwor</a>
				</div>		
				
		        <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
				
		</div>
	</div>
</div>
        <div class="modal fade" id="send_OTP" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header text-center">
                        <a class="btn pull-right" data-dismiss="modal"><span>&times;</span></a>
                        <h3 class="register_header"><strong>Please enter phone number to receive the code </strong></h3>

                    </div>
                    <div class="modal-body">
                        <asp:TextBox ID="txtPhone" CssClass="form-control"  runat="server"></asp:TextBox>
                    </div>
                    <div class="modal-footer">                     
                        <asp:Button ID="btnSendOTP" class="btn btn-success" UseSubmitBehavior="false" data-dismiss="modal" runat="server" Text="Send OTP" OnClick="btnSendOTP_Click" />                      
                    </div>
                </div>
            </div>
        </div>

       <div class="modal fade" id="Receive_OTP" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header text-center">
                        <a class="btn pull-right" data-dismiss="modal"><span>&times;</span></a>
                        <h3 class="register_header"><strong>Please enter the OTP(One Time Password) sent to your registered mobile #:974xxxx5968 </strong></h3>
                        <h4>This OTP will expire in 5 minutes.</h4>

                    </div>
                    <div class="modal-body">
                        <asp:TextBox ID="txtOTP" CssClass="form-control" placeholder="One Time Password" runat="server"></asp:TextBox>
                    </div>
                    <div class="modal-footer">                     
                        <asp:Button ID="verifyOTP" class="btn btn-success" UseSubmitBehavior="false" data-dismiss="modal" runat="server" Text="Validate OTP" OnClick="ValidateOTP_Click"/>
                        <asp:HyperLink ID="HyperLink1" runat="server">If you have not receive your OTP then click here</asp:HyperLink>
                    </div>
                </div>
            </div>
        </div>
</form>
</body>
</html>

Step 8: Here is the code for .CS page. Here I have hardcoded a few things please ignore it while you use this code in your application.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    DataTable dt = new DataTable();
    SqlCommand cmd;
    SqlDataAdapter adp = new SqlDataAdapter();
    string randomNumber;
    string Cust_No = "12345";
    string Uname = "Rswain";
    string Mobile_no = "50965968";
    HttpCookie myCookie;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            lblMsg.Visible = false;
            txtPhone.Text = string.Format("974 XXXX") + Mobile_no.Substring(Mobile_no.Length - 4, 4);
        }
    }

    public void InsertOTPinDB()
    {
        string query = "INSERT INTO OTPhistroytbl (id,Customer_No,User_Id,OTP,ctime_Stamp,status) VALUES (@id,@Customer_No,@User_Id,@OTP,@ctime_Stamp,@status) ";
        cmd = new SqlCommand(query, con);
        con.Open();
        cmd.Parameters.AddWithValue("@id", 2);
        cmd.Parameters.AddWithValue("@Customer_No", Cust_No.ToString());
        cmd.Parameters.AddWithValue("@User_Id", Uname);
        cmd.Parameters.AddWithValue("@OTP", randomNumber);
        cmd.Parameters.AddWithValue("@ctime_Stamp", System.DateTime.Now.ToString());
        cmd.Parameters.AddWithValue("@status", "1");
        cmd.ExecuteNonQuery();
        con.Close();
    }
    protected void Btnsubmit_Click(object sender, EventArgs e)
    {
        lblMsg.Visible = true;
        if (txtUser.Text == "")
        {
            lblMsg.Text = "Enter UserName";
        }
        else if (txtPassword.Text == "")
        {
            lblMsg.Text = "Enter Password";
        }
        else
        {
            try
            {
                lblMsg.Visible = false;
                adp = new SqlDataAdapter("SELECT COUNT(*) FROM Login_Check_Sp WHERE username='" + txtUser.Text + "' AND pwd='" + txtPassword.Text + "'", con);
                adp.Fill(dt);
                if (dt.Rows[0][0].ToString() == "1")
                {
                    HttpCookie userCookie = new HttpCookie("myCookie");
                    userCookie.Values.Add("customerID", Cust_No.ToString());
                    userCookie.Expires = DateTime.Now.AddHours(24);
                    Response.Cookies.Add(userCookie);
                    myCookie = Request.Cookies["myCookie"];
                    if (myCookie == null)
                    {
                        // No cookie found or cookie expired. :(
                        ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "<script>$('#send_OTP').modal('show');</script>", false);

                    }

                    // Verify the cookie value
                    if (!string.IsNullOrEmpty(myCookie.Values["customerID"]))  // userId is found
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "<script>$('#send_OTP').modal('show');</script>", false);
                        string userId = myCookie.Values["customerID"].ToString();

                        String result;
                        String name = txtOTP.Text;
                        string apiKey = "DrXhf8CYfmQ-NcAXvBPyPySQXYmDwfBlnBNBJPt7dQ";
                        string numbers = Mobile_no.ToString();
                        Random rnd = new Random();
                        randomNumber = (rnd.Next(100000, 999999)).ToString();

                        string message = "Hey " + name + "your otp is " + randomNumber;
                        string send = "enjoysharepoint";

                        String url = "https://api.txtlocal.com/send/?apikey=" + apiKey + "&numbers=" + numbers + "&message=" + message + "&sender=" + send;
                        //refer to parameters to complete correct url string

                        StreamWriter myWriter = null;
                        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);

                        objRequest.Method = "POST";
                        objRequest.ContentLength = Encoding.UTF8.GetByteCount(url);
                        objRequest.ContentType = "application/x-www-form-urlencoded";
                        try
                        {
                            myWriter = new StreamWriter(objRequest.GetRequestStream());
                            myWriter.Write(url);
                            InsertOTPinDB();
                        }
                        catch (Exception eX)
                        {
                            lblMsg.Text = eX.Message;
                        }
                        finally
                        {
                            myWriter.Close();
                        }
                        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
                        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
                        {
                            result = sr.ReadToEnd();
                            // Close and clean up the StreamReader
                            sr.Close();
                        }
                        lblMsg.Text = result;
                    }

                    if (Request.Cookies["customerID"] != null)
                    {
                        // This will delete the cookie userId
                        Response.Cookies["customerID"].Expires = DateTime.Now.AddDays(-1);
                        lblMsg.Text = "logined successfully";
                    }
                }
                else
                {
                    lblMsg.Text = "Wrong Username/Password";
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
                // Response.Write("Oops!! following error occured: " +ex.Message.ToString());           
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
                adp.Dispose();
            }
        }
    }
    protected void btnSendOTP_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "<script>$('#Receive_OTP').modal('show');</script>", false);
    }

    protected void ValidateOTP_Click(object sender, EventArgs e)
    {
        lblMsg.Visible = true;
        adp = new SqlDataAdapter("SELECT ctime_Stamp FROM OTPhistroytbl WHERE OTP='" + txtOTP.Text + "'", con);
        adp.Fill(dt);
        DateTime OtpCrtDate = Convert.ToDateTime(dt.Rows[0][0].ToString());

        if (txtOTP.Text != randomNumber)
        {
            TimeSpan timeSub = DateTime.Now - OtpCrtDate;
            if (timeSub.TotalMinutes < 300)
            {
                cmd = new SqlCommand("update OTPhistroytbl set status='0' where OTP='" + txtOTP.Text + "'", con);
                con.Open();
                cmd.ExecuteNonQuery();
                lblMsg.Text = "logined successfully";
                con.Close();
            }
            else
            {
                lblMsg.Text = "Sorry but your OTP is very old. Get a new one";
            }
        }
        else
        {

            lblMsg.Text = "Sorry, Your OTP is Invalid. Try again, please.";
        }
    }
}

Note: For sending OTP to mobile, It may not be work for you because this key doesn’t work for you. You have to generate your own key to sending OTP to your mobile or you can use this OTP while sending in an email instead of sending as SMS in mobile.

Step 9: Please look into my OTP result in a SQL database which is shown below. Here Id, Customer_no, and User_Id should populate dynamically as I have hardcoded here.

Generate One Time Password (OTP) in Asp.Net using C#.Net
Generate One Time Password (OTP) in Asp.Net using C#.Net

Please try with your end and let me know if anyone facing any problem.

You may like following asp.net tutorials:

Hope this asp.net tutorial explains, how to generate otp in asp.net using c#.net.

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

Rajkiran Swain

Rajkiran is currently working as a SharePoint Consultant in QATAR . Rajkiran having 6 + years of experience in Microsoft Technologies such as SharePoint 2019/2016/2013/2010, MOSS 2007,WSS 3.0, Migration, Asp.Net, C#.Net, Sql Server, Ajax, jQuery etc.He is C#Corner MVP (2 Times).

>