python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions