forgot password in mvc 5 asp.net

How do I implement forgot password in Asp.Net MVC 5?

Hello everyone, I am going to share the code sample with simple steps for forgot password or reset password using Asp.Net MVC 5

The Steps of forgot password as given below. 

Step 1 : First click on forgot links. 
Step 2 : Enter valid emailId in input text box. 
Step 3 : Validate emailId, If email valid sent an email to given email with attached links. Step 4 : Click on given email links, open a popup with new pwd and confirm pwd. 
Step 5 : Click on reset pwd, If valid pwd then sent successfully msg on below popup box, otherwise send error msg for invalid attempt. 

The Code-Sample steps as give below. 

Step 1. Click on forgot link, enter email and validate it. If email is valid then sent an email link to your given email Id.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//Step 1 : Forgot password  HTTP post action method
 [HttpPost]
 [AllowAnonymous]
 [ValidateAntiForgeryToken]
  public async Task<ActionResult> ForgotPassword(ForgotViewModel model)
  {
      if (ModelState.IsValid)
       {
            var user = await UserManager.FindByNameAsync(model.UserName);
            string To = model.UserName, UserID, Password, SMTPPort, Host;      
             if (user == null) {
                    // If user does not exist or is not confirmed.
                    return View("ForgotPassword");
              } else {
            //Generate password token
             var guid= Guid.NewGuid();
             //Create URL with above token
             var lnkHref= "<a href='" + Url.Action("ResetPassword", "Account", new { email= model.UserName, code = guid}, "http") + "'>Reset Password</a>";
             //HTML Template for Send email
             string subject = "Your changed password";
             string body = "<b>Please find the Password Reset Link. </b><br/>" + lnkHref;
            //Get and set the AppSettings using configuration manager.
             EmailManager.AppSettings(out UserID, out Password, out SMTPPort, out Host);
             //Call send email methods.
              EmailManager.SendEmail(UserID, subject, body, To, UserID, Password, SMTPPort, Host);
              }
           }
           return View();
     }
    // If we got this far, something failed, re-display form
    return View(model);
 }
//Step 2 : Email Manager class
public class EmailManager
{
    public static void AppSettings(out string UserID, out string Password, out string SMTPPort, out string Host)
    {
         UserID = ConfigurationManager.AppSettings.Get("UserID");
         Password = ConfigurationManager.AppSettings.Get("Password");
         SMTPPort = ConfigurationManager.AppSettings.Get("SMTPPort");
         Host = ConfigurationManager.AppSettings.Get("Host");
    }
public static void SendEmail(string From, string Subject, string Body, string To, string UserID, string Password, string SMTPPort, string Host)
{
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                mail.To.Add(To);
                mail.From = new MailAddress(From);
                mail.Subject = Subject;
                mail.Body = Body;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = Host;
                smtp.Port = Convert.ToInt16(SMTPPort);
                smtp.Credentials = new NetworkCredential(UserID, Password);             
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
      }     
}
//Step 3: App setting for the configuration manager
 <appSettings>
    <add key="ToEmail" value="[email protected]" />
    <add key="UserID" value="[email protected]" />
    <add key="Password" value="enterpassordhere" />
    <add key="SMTPPort" value="587" />
    <add key="Host" value="smtp.gmail.com" />
  </appSettings>
//Step 1 : Forgot password  HTTP post action method

 [HttpPost]
 [AllowAnonymous]
 [ValidateAntiForgeryToken]
  public async Task<ActionResult> ForgotPassword(ForgotViewModel model)
  {
      if (ModelState.IsValid)
       {
            var user = await UserManager.FindByNameAsync(model.UserName);
            string To = model.UserName, UserID, Password, SMTPPort, Host;       
             if (user == null) {
                    // If user does not exist or is not confirmed.
                    return View("ForgotPassword");
              } else {
            //Generate password token
             var guid= Guid.NewGuid();

             //Create URL with above token
             var lnkHref= "<a href='" + Url.Action("ResetPassword", "Account", new { email= model.UserName, code = guid}, "http") + "'>Reset Password</a>";

             //HTML Template for Send email
             string subject = "Your changed password";
             string body = "<b>Please find the Password Reset Link. </b><br/>" + lnkHref;

            //Get and set the AppSettings using configuration manager.
             EmailManager.AppSettings(out UserID, out Password, out SMTPPort, out Host);

             //Call send email methods.
              EmailManager.SendEmail(UserID, subject, body, To, UserID, Password, SMTPPort, Host);
              }
           }
           return View();
     }
    // If we got this far, something failed, re-display form
    return View(model);
 }

//Step 2 : Email Manager class

public class EmailManager
{
    public static void AppSettings(out string UserID, out string Password, out string SMTPPort, out string Host)
    {
         UserID = ConfigurationManager.AppSettings.Get("UserID");
         Password = ConfigurationManager.AppSettings.Get("Password");
         SMTPPort = ConfigurationManager.AppSettings.Get("SMTPPort");
         Host = ConfigurationManager.AppSettings.Get("Host");
    }

public static void SendEmail(string From, string Subject, string Body, string To, string UserID, string Password, string SMTPPort, string Host)
{
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                mail.To.Add(To);
                mail.From = new MailAddress(From);
                mail.Subject = Subject;
                mail.Body = Body;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = Host;
                smtp.Port = Convert.ToInt16(SMTPPort);
                smtp.Credentials = new NetworkCredential(UserID, Password);              
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
      }      
}

//Step 3: App setting for the configuration manager

 <appSettings>
    <add key="ToEmail" value="[email protected]" />
    <add key="UserID" value="[email protected]" />
    <add key="Password" value="enterpassordhere" />
    <add key="SMTPPort" value="587" />
    <add key="Host" value="smtp.gmail.com" />
  </appSettings>
Step 2. After Click on given email link, open a popup with new pwd and confirm pwd. If the attempt is valid then sent successfully msg on below popup box otherwise send error msg for invalid attempt.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/// <summary>
        /// This method is used to handle the post events for ResetPassword.
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult ResetPassword(ResetPwdViewModel model, string email, string code)
        {
            if (ModelState.IsValid)
            {
                AspNetUser user = _repoAspDotNetUser.GetAspNetUser(email);
                 if (user != null)
                 {
                     String hashedNewPassword = userManager.PasswordHasher.HashPassword(model.Password);
                     bool result = _repoAspDotNetUser.ResetPasswordByToken(email, code, hashedNewPassword);
                     if (result)
                     {
                         ModelState.AddModelError("", "Please return to the login page and enjoy with new password.");
                     }
                 }
                 else
                 {
                     ModelState.AddModelError("", "It's not a valid, this attempt is already processed.");
                 }
            }
            return View();
        }
/// <summary>
        /// This method is used to handle the post events for ResetPassword.
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult ResetPassword(ResetPwdViewModel model, string email, string code)
        {
            if (ModelState.IsValid)
            {
                AspNetUser user = _repoAspDotNetUser.GetAspNetUser(email);
                 if (user != null)
                 {
                     String hashedNewPassword = userManager.PasswordHasher.HashPassword(model.Password);
                     bool result = _repoAspDotNetUser.ResetPasswordByToken(email, code, hashedNewPassword);
                     if (result)
                     {
                         ModelState.AddModelError("", "Please return to the login page and enjoy with new password.");
                     }
                 }
                 else
                 {
                     ModelState.AddModelError("", "It's not a valid, this attempt is already processed.");
                 }
            }
            return View();
        }
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book