How to create Login Page using Asp.net MVC using stored procedure with phone OTP step by step ?

Creating a login page in ASP.NET MVC that uses a phone OTP (One-Time Password) for authentication involves several steps. This guide will walk you through the process step-by-step, including setting up the database, creating a stored procedure, and implementing the ASP.NET MVC application.

Step 1: Set Up Your ASP.NET MVC Project

Open Visual Studio.

Create a new ASP.NET MVC project:

Go to File > New > Project.

Select ASP.NET Web Application and name your project (e.g., PhoneOtpLoginApp).

Choose the MVC template and click OK.

Step 2: Set Up the Database

Create a SQL Server Database:

Open SQL Server Management Studio (SSMS).

Create a new database named UserDB.

Create a Users Table:

Execute the following SQL script to create a table for storing user credentials:

sql

CREATE TABLE Users (

Id INT PRIMARY KEY IDENTITY(1,1),

PhoneNumber VARCHAR(15) NOT NULL,

Otp VARCHAR(6) NOT NULL,

IsVerified BIT DEFAULT 0

);

Insert Sample Data:

You can add a sample user for testing:

sql

INSERT INTO Users (PhoneNumber, Otp, IsVerified) VALUES (‘1234567890’, ”, 0);

Create a Stored Procedure:

Create a stored procedure to validate the OTP:

sql

CREATE PROCEDURE ValidateUserOtp

@PhoneNumber VARCHAR(15),

@Otp VARCHAR(6)

AS

BEGIN

UPDATE Users SET IsVerified = 1 WHERE PhoneNumber = @PhoneNumber AND Otp = @Otp;

SELECT @@ROWCOUNT AS ‘RowsAffected’;

END

Step 3: Create the Model

Create a Model Class:

In the Models folder, create a new class named LoginModel.cs:

csharp

public class LoginModel

{

public string PhoneNumber { get; set; }

public string Otp { get; set; }

}

Step 4: Create the Controller

Create a Controller:

Right-click on the Controllers folder and add a new controller named AccountController.cs:

csharp

using System;

using System.Data;

using System.Data.SqlClient;

using System.Net;

using System.Net.Mail;

using System.Web.Mvc;

using YourNamespace.Models; // Update with your actual namespace

using Twilio;

using Twilio.Rest.Api.V2010.Account;

using Twilio.Types;

public class AccountController : Controller

{

private string connectionString = “YourConnectionStringHere”; // Update with your connection string

public ActionResult Login()

{

return View();

}

[HttpPost]

public ActionResult Login(LoginModel model)

{

if (ModelState.IsValid)

{

// Generate OTP

var otp = new Random().Next(100000, 999999).ToString();

// Store OTP in the database

using (SqlConnection conn = new SqlConnection(connectionString))

{

SqlCommand cmd = new SqlCommand(“UPDATE Users SET Otp = @Otp WHERE PhoneNumber = @PhoneNumber”, conn);

cmd.Parameters.AddWithValue(“@Otp”, otp);

cmd.Parameters.AddWithValue(“@PhoneNumber”, model.PhoneNumber);

conn.Open();

cmd.ExecuteNonQuery();

}

// Send OTP via SMS

SendOtpSms(model.PhoneNumber, otp);

// Redirect to OTP verification

return RedirectToAction(“VerifyOtp”, new { phoneNumber = model.PhoneNumber });

}

return View(model);

}

public ActionResult VerifyOtp(string phoneNumber)

{

ViewBag.PhoneNumber = phoneNumber;

return View();

}

[HttpPost]

public ActionResult VerifyOtp(LoginModel model)

{

if (ModelState.IsValid)

{

using (SqlConnection conn = new SqlConnection(connectionString))

{

SqlCommand cmd = new SqlCommand(“ValidateUserOtp”, conn);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue(“@PhoneNumber”, model.PhoneNumber);

cmd.Parameters.AddWithValue(“@Otp”, model.Otp);

conn.Open();

var rowsAffected = (int)cmd.ExecuteScalar();

if (rowsAffected > 0)

{

// OTP verified successfully

return RedirectToAction(“Index”, “Home”); // Redirect to home page

}

else

{

ModelState.AddModelError(“”, “Invalid OTP. Please try again.”);

}

}

}

return View(model);

}

private void SendOtpSms(string phoneNumber, string otp)

{

const string accountSid = “YOUR_TWILIO_ACCOUNT_SID”; // Replace with your Twilio account SID

const string authToken = “YOUR_TWILIO_AUTH_TOKEN”; // Replace with your Twilio auth token

const string fromPhoneNumber = “YOUR_TWILIO_PHONE_NUMBER”; // Replace with your Twilio phone number

TwilioClient.Init(accountSid, authToken);

var message = MessageResource.Create(

body: $”Your OTP is {otp}.”,

from: new PhoneNumber(fromPhoneNumber),

to: new PhoneNumber(phoneNumber)

);

}

}

Step 5: Create the Views

Create the Login View:

Right-click on the Login action in AccountController and select Add View.

Name the view Login.cshtml and use the LoginModel as the model.

xml

@model YourNamespace.Models.LoginModel

@{

ViewBag.Title = “Login”;

}

<h2>Login</h2>

@using (Html.BeginForm())

{

@Html.AntiForgeryToken()

<div>

@Html.LabelFor(m => m.PhoneNumber)

@Html.TextBoxFor(m => m.PhoneNumber)

@Html.ValidationMessageFor(m => m.PhoneNumber)

</div>

<div>

<input type=”submit” value=”Send OTP” />

</div>

}

Create the Verify OTP View:

Right-click on the VerifyOtp action in AccountController and select Add View.

Name the view VerifyOtp.cshtml and use the LoginModel as the model.

xml

@model YourNamespace.Models.LoginModel

@{

ViewBag.Title = “Verify OTP”;

}

<h2>Verify OTP</h2>

@using (Html.BeginForm())

{

@Html.AntiForgeryToken()

<div>

@Html.HiddenFor(m => m.PhoneNumber)

@Html.LabelFor(m => m.Otp)

@Html.TextBoxFor(m => m.Otp)

@Html.ValidationMessageFor(m => m.Otp)

</div>

<div>

<input type=”submit” value=”Verify OTP” />

</div>

}

Step 6: Configure the Connection String

Update Connection String:

Open Web.config and add your connection string inside the <connectionStrings> section:

xml

<connectionStrings>

<add name=”DefaultConnection” connectionString=”Data Source=YOUR_SERVER;Initial Catalog=UserDB;Integrated Security=True” providerName=”System.Data.SqlClient” />

</connectionStrings>

Update the connectionString variable in the AccountController to use this connection string:

csharp

private string connectionString = ConfigurationManager.ConnectionStrings[“DefaultConnection”].ConnectionString;

Step 7: Set Up Twilio for SMS

Sign Up for Twilio:

Go to Twilio and create an account.

Obtain your Account SID, Auth Token, and a Twilio phone number.

Install Twilio NuGet Package:

Use the NuGet Package Manager to install the Twilio SDK:

text

Install-Package Twilio

Step 8: Run Your Application

Start the Application:

Press F5 to run your application.

Navigate to /Account/Login to access the login page.

Enter a phone number and click Send OTP.

Check the phone for the OTP and enter it on the verification page.

Conclusion

This post explains how to establish a login page in ASP.NET MVC utilizing a phone OTP for authentication. You can improve this implementation by including features like:

  • Error handling for failed SMS sending.
  • OTP expiration to enhance security.
  • Password hashing if you decide to store passwords in the database in the future.

This implementation sends SMS via Twilio, but you can use any SMS gateway service that meets your needs.

Leave a Comment

Your email address will not be published. Required fields are marked *