How to create forget password in Login page using Asp.net MVC step by step ?

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

  1. Create a New ASP.NET MVC Project:
    • Open Visual Studio.
    • Go to File > New > Project.
    • Choose ASP.NET Web Application, select MVC, and click OK.
  2. 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), and ResetToken (nvarchar).

Step 2: Set Up Models

  1. Create a User Model:
    • In the Models folder, create a User.cs class.

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 and ResetPasswordViewModel.cs in the Models 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

  1. Create UserContext.cs:
    • Create a class in the Models folder for Entity Framework to handle database interactions.

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

  1. Create Forgot Password View:
    • Create a folder named Account under the Views folder.
    • Right-click the Account folder, add a new view named ForgotPassword.cshtml.

@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 the Account 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

  1. Create AccountController:
    • In the Controllers folder, add a new controller named AccountController.

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 the SendResetEmail method with your actual SMTP server credentials, such as host, port, and credentials for sending emails.

Step 7: Test the Application

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

  1. 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.
  2. Create Models: Set up a User model to represent the users and create view models for handling the “Forgot Password” and “Reset Password” actions.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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!

Leave a Comment

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