Create a Login Page with CAPTCHA in ASP.NET MVC

Step 1: Set Up the Project

  1. Create a New ASP.NET MVC Project:
    • Open Visual Studio.
    • Go to File > New > Project.
    • Select ASP.NET Web Application, choose MVC, and click OK.
  2. Create the Database:
    • Add a SQL Server database to the project (LoginDB.mdf).
    • Create a table Users with columns UserId (int, Primary Key, Identity), Username (nvarchar), and Password (nvarchar).

Step 2: Add reCAPTCHA to the Project

  1. Register for Google reCAPTCHA:
  2. 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 like reCAPTCHA.AspNetCore or a similar package for ASP.NET MVC.
  3. Add reCAPTCHA Keys to Web.config:
    • Add your Site Key and Secret Key in the Web.config file inside the <appSettings> section.

xml

<appSettings>

<add key=”Recaptcha:SiteKey” value=”YOUR_SITE_KEY” />

<add key=”Recaptcha:SecretKey” value=”YOUR_SECRET_KEY” />

</appSettings>

Step 3: Set Up Models

  1. Create a User Model:
    • Right-click on the Models folder, add a class named User.cs, and define the model.

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 the Models 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

  1. Create a Database Context:
    • Add a UserContext.cs class in the Models folder.

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

  1. Create the Login View:
    • Create a folder named Account under the Views folder.
    • Add a new view named Login.cshtml under the Account folder.

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

  1. Create AccountController:
    • Right-click on the Controllers folder, add a new controller named AccountController.

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

  1. Ensure your application is running over HTTPS to avoid reCAPTCHA issues related to insecure contexts.

Step 8: Run and Test the Application

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

  1. 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.
  2. 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.
  3. Create Models: Set up a User model to represent user data and a LoginViewModel to handle login inputs and CAPTCHA responses.
  4. Create Database Context: Define a UserContext class to handle interactions with the database using Entity Framework, and configure the database connection in Web.config.
  5. 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.
  6. 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.
  7. 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.

Leave a Comment

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