Step 1: Set Up the Project
- Create a New ASP.NET MVC Project:
- Open Visual Studio.
- Go to
File
>New
>Project
. - Select
ASP.NET Web Application
, chooseMVC
, and clickOK
.
- Create the Database:
- Add a SQL Server database to the project (
LoginDB.mdf
). - Create a table
Users
with columnsUserId (int, Primary Key, Identity)
,Username (nvarchar)
, andPassword (nvarchar)
.
- Add a SQL Server database to the project (
Step 2: Add reCAPTCHA to the Project
- Register for Google reCAPTCHA:
- Go to Google reCAPTCHA Admin Console.
- Register your site and get the Site Key and Secret Key.
- Install reCAPTCHA NuGet Package:
- Open the NuGet Package Manager (
Tools > NuGet Package Manager > Manage NuGet Packages for Solution
). - Search for
reCAPTCHA
, and install a package likereCAPTCHA.AspNetCore
or a similar package for ASP.NET MVC.
- Open the NuGet Package Manager (
- Add reCAPTCHA Keys to Web.config:
- Add your Site Key and Secret Key in the
Web.config
file inside the<appSettings>
section.
- Add your Site Key and Secret Key in the
xml
<appSettings>
<add key=”Recaptcha:SiteKey” value=”YOUR_SITE_KEY” />
<add key=”Recaptcha:SecretKey” value=”YOUR_SECRET_KEY” />
</appSettings>
Step 3: Set Up Models
- Create a User Model:
- Right-click on the
Models
folder, add a class namedUser.cs
, and define the model.
- Right-click on the
C#:
using System.ComponentModel.DataAnnotations;
public class User
{
public int UserId { get; set; }
[Required(ErrorMessage = “Username is required”)]
public string Username { get; set; }
[Required(ErrorMessage = “Password is required”)]
[DataType(DataType.Password)]
public string Password { get; set; }
}
2. Create a ViewModel for Login:
- Add a
LoginViewModel.cs
in theModels
folder to handle user input and reCAPTCHA validation.
C#
using System.ComponentModel.DataAnnotations;
public class LoginViewModel
{
[Required(ErrorMessage = “Username is required”)]
public string Username { get; set; }
[Required(ErrorMessage = “Password is required”)]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = “Captcha is required”)]
public string CaptchaResponse { get; set; }
}
Step 4: Create a Data Access Layer
- Create a Database Context:
- Add a
UserContext.cs
class in theModels
folder.
- Add a
C#
using System.Data.Entity;
public class UserContext : DbContext
{
public DbSet<User> Users { get; set; }
}
2. Configure the Connection String:
- Add the connection string to the
Web.config
file.
xml
<connectionStrings>
<add name=”UserContext”
connectionString=”Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=LoginDB;Integrated Security=True”
providerName=”System.Data.SqlClient” />
</connectionStrings>
Step 5: Create the Login View
- Create the Login View:
- Create a folder named
Account
under theViews
folder. - Add a new view named
Login.cshtml
under theAccount
folder.
- Create a folder named
html
@model YourNamespace.Models.LoginViewModel
@{
ViewBag.Title = “Login”;
}
<h2>Login</h2>
@using (Html.BeginForm(“Login”, “Account”, FormMethod.Post))
{
@Html.ValidationSummary(true)
<div>
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username)
</div>
<div>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</div>
<div>
<label>Captcha:</label>
<div class=”g-recaptcha” data-sitekey=”@System.Configuration.ConfigurationManager.AppSettings[“Recaptcha:SiteKey”]”></div>
</div>
<button type=”submit”>Login</button>
}
<script src=”https://www.google.com/recaptcha/api.js” async defer></script>
Step 6: Create the Account Controller
- Create
AccountController
:- Right-click on the
Controllers
folder, add a new controller namedAccountController
.
- Right-click on the
C#:
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Mvc;
using YourNamespace.Models;
using Newtonsoft.Json;
public class AccountController : Controller
{
private UserContext db = new UserContext();
// GET: Account/Login
public ActionResult Login()
{
return View();
}
// POST: Account/Login
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
// Validate reCAPTCHA
var isCaptchaValid = await ValidateCaptcha(model.CaptchaResponse);
if (!isCaptchaValid)
{
ModelState.AddModelError(“”, “Invalid Captcha. Please try again.”);
return View(model);
}
// Check user credentials
var user = db.Users.FirstOrDefault(u => u.Username == model.Username && u.Password == model.Password);
if (user != null)
{
Session[“Username”] = user.Username;
return RedirectToAction(“Index”, “Home”);
}
else
{
ModelState.AddModelError(“”, “Invalid Username or Password”);
}
}
return View(model);
}
private async Task<bool> ValidateCaptcha(string captchaResponse)
{
var secretKey = System.Configuration.ConfigurationManager.AppSettings[“Recaptcha:SecretKey”];
var httpClient = new HttpClient();
var response = await httpClient.GetStringAsync(
$”https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={captchaResponse}”);
dynamic jsonResponse = JsonConvert.DeserializeObject(response);
return jsonResponse.success == “true”;
}
}
Step 7: Update Web.config
for HTTPS
- Ensure your application is running over HTTPS to avoid reCAPTCHA issues related to insecure contexts.
Step 8: Run and Test the Application
- Run the Application:
- Test the login functionality with CAPTCHA verification.
- Verify that valid logins proceed and invalid CAPTCHA attempts are blocked.
This configuration in ASP.NET MVC creates a secure login page utilizing CAPTCHA, which helps guard against automated bot assaults. Please let me know if you need any more modification or clarification!
Summary
- Set Up the Project: Start by creating an ASP.NET MVC project in Visual Studio, then add a SQL Server database and set up a
Users
table to store user credentials. - Add reCAPTCHA: Register your site on the Google reCAPTCHA platform to get the necessary keys (Site Key and Secret Key). Add these keys to your project’s configuration (
Web.config
), and install a reCAPTCHA NuGet package for ASP.NET MVC. - Create Models: Set up a
User
model to represent user data and aLoginViewModel
to handle login inputs and CAPTCHA responses. - Create Database Context: Define a
UserContext
class to handle interactions with the database using Entity Framework, and configure the database connection inWeb.config
. - Build the Login View: Create a login page (
Login.cshtml
) where users can enter their credentials and solve the CAPTCHA challenge. Integrate reCAPTCHA by adding its script and widget to the view. - Create the Account Controller: Develop an
AccountController
with actions to handle the login process, including CAPTCHA validation. If the CAPTCHA is validated and the credentials are correct, the user is logged in; otherwise, appropriate error messages are shown. - Run and Test: Finally, run the application to ensure that the login works as expected, including correct CAPTCHA functionality.
This setup ensures your login page is secure, protecting it from bot attacks using CAPTCHA validation.