Creating a “Forgot Password” feature in an ASP.NET MVC application involves steps for requesting a password reset, sending a reset link via email, and updating the password securely. Below is a step-by-step guide to implementing a “Forgot Password” functionality:
Step-by-Step Guide to Create a Forgot Password Feature in ASP.NET MVC
Step 1: Set Up the Project
- Create a New ASP.NET MVC Project:
- Open Visual Studio.
- Go to
File
>New
>Project
. - Choose
ASP.NET Web Application
, selectMVC
, and clickOK
.
- Set Up the Database:
- Add a SQL Server database to the project (
LoginDB.mdf
). - Create a
Users
table with columns:UserId (int, Primary Key, Identity)
,Username (nvarchar)
,Email (nvarchar)
,Password (nvarchar)
, andResetToken (nvarchar)
.
- Add a SQL Server database to the project (
Step 2: Set Up Models
- Create a User Model:
- In the
Models
folder, create aUser.cs
class.
- In the
using System.ComponentModel.DataAnnotations;
public class User
{
public int UserId { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public string ResetToken { get; set; }
}
2. Create a ViewModel for Forgot Password and Reset Password:
- Create
ForgotPasswordViewModel.cs
andResetPasswordViewModel.cs
in theModels
folder.
public class ForgotPasswordViewModel
{
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
}
public class ResetPasswordViewModel
{
[Required]
public string Token { get; set; }
[Required(ErrorMessage = "New Password is required")]
[DataType(DataType.Password)]
public string NewPassword { get; set; }
[Required(ErrorMessage = "Confirm Password is required")]
[DataType(DataType.Password)]
[Compare("NewPassword", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
Step 3: Create the Database Context
- Create
UserContext.cs
:- Create a class in the
Models
folder for Entity Framework to handle database interactions.
- Create a class in the
using System.Data.Entity;
public class UserContext : DbContext
{
public DbSet Users { get; set; }
}
2. Configure Connection String:
- Add a connection string in 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 4: Create Forgot Password and Reset Password Views
- Create Forgot Password View:
- Create a folder named
Account
under theViews
folder. - Right-click the
Account
folder, add a new view namedForgotPassword.cshtml
.
- Create a folder named
@model YourNamespace.Models.ForgotPasswordViewModel
<h2>Forgot Password </h2>
@using (Html.BeginForm("ForgotPassword", "Account", FormMethod.Post))
{
@Html.ValidationSummary(true)
<div>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</div>
<button type="submit">Send Reset Link</button>
}
2. Create Reset Password View:
- Add a new view named
ResetPassword.cshtml
under theAccount
folder.
@model YourNamespace.Models.ResetPasswordViewModel
<h2> Reset Password </h2>
@using (Html.BeginForm("ResetPassword", "Account", FormMethod.Post))
{
@Html.HiddenFor(m => m.Token)
@Html.ValidationSummary(true)
<div>
@Html.LabelFor(m => m.NewPassword)
@Html.PasswordFor(m => m.NewPassword)
</div>
<div>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</div>
<button type="submit">Reset Password</button>
}
Step 5: Create Account Controller
- Create
AccountController
:- In the
Controllers
folder, add a new controller namedAccountController
.
- In the
using System;
using System.Linq;
using System.Web.Mvc;
using YourNamespace.Models;
using System.Net.Mail; // For sending emails
public class AccountController : Controller
{
private UserContext db = new UserContext();
// GET: Account/ForgotPassword
public ActionResult ForgotPassword()
{
return View();
}
// POST: Account/ForgotPassword
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = db.Users.FirstOrDefault(u => u.Email == model.Email);
if (user != null)
{
// Generate reset token
user.ResetToken = Guid.NewGuid().ToString();
db.SaveChanges();
// Send reset email
var resetLink = Url.Action("ResetPassword", "Account", new { token = user.ResetToken }, Request.Url.Scheme);
SendResetEmail(user.Email, resetLink);
ViewBag.Message = "A password reset link has been sent to your email.";
return View();
}
else
{
ModelState.AddModelError("", "Email not found.");
}
}
return View(model);
}
// GET: Account/ResetPassword
public ActionResult ResetPassword(string token)
{
var user = db.Users.FirstOrDefault(u => u.ResetToken == token);
if (user == null)
{
return HttpNotFound();
}
var model = new ResetPasswordViewModel { Token = token };
return View(model);
}
// POST: Account/ResetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ResetPassword(ResetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = db.Users.FirstOrDefault(u => u.ResetToken == model.Token);
if (user != null)
{
user.Password = model.NewPassword; // In production, hash this password!
user.ResetToken = null; // Clear the reset token
db.SaveChanges();
ViewBag.Message = "Password has been reset successfully.";
return RedirectToAction("Login");
}
else
{
ModelState.AddModelError("", "Invalid token.");
}
}
return View(model);
}
private void SendResetEmail(string email, string resetLink)
{
// Example email sending code (customize SMTP settings accordingly)
var mail = new MailMessage("no-reply@yourdomain.com", email)
{
Subject = "Password Reset",
Body = $"Please reset your password using the following link: {resetLink}",
IsBodyHtml = true
};
using (var smtp = new SmtpClient("smtp.yourdomain.com"))
{
smtp.Send(mail);
}
}
}
Step 6: Configure Email Settings
- Update Email Settings: Make sure to update the
SmtpClient
settings in theSendResetEmail
method with your actual SMTP server credentials, such as host, port, and credentials for sending emails.
Step 7: Test the Application
- Run the Application:
- Test the Forgot Password functionality by entering an email address.
- Check that the reset link is sent correctly, and the password is reset upon successful verification.
This approach adds a robust “Forgot Password” feature to your ASP.NET MVC application, enhancing user experience and security. Let me know if you need further assistance or customization!
Summary:
- Set Up the Project: Create an ASP.NET MVC project in Visual Studio and add a SQL Server database with a
Users
table to store user credentials, including fields for the reset token. - Create Models: Set up a
User
model to represent the users and create view models for handling the “Forgot Password” and “Reset Password” actions. - Set Up Database Context: Create a
UserContext
class to interact with the database using Entity Framework and configure the database connection in the project settings. - Build the Views: Design views for “Forgot Password” and “Reset Password.” The “Forgot Password” view allows users to enter their email address to request a reset link, and the “Reset Password” view lets users set a new password.
- Create the Account Controller: Develop an
AccountController
with actions to handle the password reset process:- Forgot Password Action: Generates a unique reset token, saves it to the database, and sends a reset link to the user’s email.
- Reset Password Action: Verifies the reset token, allows the user to set a new password, and clears the reset token once the password is updated.
- Send Reset Emails: Implement a simple email function that sends the password reset link to the user. Ensure you configure your SMTP settings correctly for this.
- Test the Application: Run the app, test the process by requesting a password reset, and confirm that you can reset your password using the link provided in the email.
By safely changing their passwords, users can easily retrieve their accounts with the help of this setup!