To create a login page in ASP.NET MVC that uses a stored procedure for authentication and includes CAPTCHA for security, follow these detailed steps:
Step 1: Create a New 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., CaptchaLoginApp).
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),
Username VARCHAR(50) NOT NULL,
Password VARCHAR(50) NOT NULL
);
Insert Sample Data:
Add a sample user for testing:
sql
INSERT INTO Users (Username, Password) VALUES (‘testuser’, ‘password123’);
Create a Stored Procedure:
Create a stored procedure to validate user credentials:
sql
CREATE PROCEDURE ValidateUserLogin
@Username VARCHAR(50),
@Password VARCHAR(50)
AS
BEGIN
SELECT FROM Users WHERE Username = @Username AND Password = @Password;
END
Step 3: Install CAPTCHA Library
Install reCAPTCHA:
Go to the Google reCAPTCHA site and register your site to get the Site Key and Secret Key.
You can use reCAPTCHA v2 for this example.
Add reCAPTCHA to Your Project:
Include the reCAPTCHA script in your layout file (e.g., _Layout.cshtml):
xml
<script src=”https://www.google.com/recaptcha/api.js” async defer></script>
Step 4: Create the Model
Create a Model Class:
In the Models folder, create a new class named LoginModel.cs:
csharp
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
public string RecaptchaResponse { get; set; }
}
Step 5: 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.Http;
using System.Threading.Tasks;
using System.Web.Mvc;
using YourNamespace.Models; // Update with your actual namespace
public class AccountController : Controller
{
private string connectionString = “YourConnectionStringHere”; // Update with your connection string
private const string RecaptchaSecretKey = “YOUR_SECRET_KEY”; // Update with your secret key
public ActionResult Login()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Login(LoginModel model)
{
if (ModelState.IsValid)
{
// Verify reCAPTCHA
var isCaptchaValid = await VerifyCaptcha(model.RecaptchaResponse);
if (!isCaptchaValid)
{
ModelState.AddModelError(“”, “Please complete the CAPTCHA.”);
return View(model);
}
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(“ValidateUserLogin”, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(“@Username”, model.Username);
cmd.Parameters.AddWithValue(“@Password”, model.Password);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
// Login successful
return RedirectToAction(“Index”, “Home”); // Redirect to home page
}
else
{
ModelState.AddModelError(“”, “Invalid username or password.”);
}
}
}
return View(model);
}
private async Task<bool> VerifyCaptcha(string response)
{
using (var client = new HttpClient())
{
var result = await client.GetStringAsync($”https://www.google.com/recaptcha/api/siteverify?secret={RecaptchaSecretKey}&response={response}”);
dynamic jsonData = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
return jsonData.success == “true”;
}
}
}
Step 6: Create the Login View
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.Username)
@Html.TextBoxFor(m => m.Username)
@Html.ValidationMessageFor(m => m.Username)
</div>
<div>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class=”g-recaptcha” data-sitekey=”YOUR_SITE_KEY”></div> <!– Replace with your site key –>
<div>
<input type=”submit” value=”Login” />
</div>
}
Step 7: 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 8: Run Your Application
Start the Application:
Press F5 to run your application.
Navigate to /Account/Login to access the login page.
Enter the username and password and complete the CAPTCHA.
Conclusion:
This post explains how to establish a login page in ASP.NET MVC utilizing a stored procedure for authentication and a CAPTCHA for added security. You may improve this implementation by including features like password hashing, account lockout after several failed tries, and user registration.