Membership Forgot Password in MVC 4

The controller and View for Membership Forgot Password in MVC 4 is added by default in Account controller and the view is added in View -> Account -> ForgotPassword.cshtml.

The link for Forgot password is given in the Login page as shown in the below image.

Membership forgot password link

On clicking link it will redirect to Forgot password page where the user needs to enter the user name for which the password has been forgotten.

Forgot password page

Validation for empty user user name is added in the controller’s forgot password post method.

Forgot password Controller

[AllowAnonymous]
        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ForgotPassword(string UserName)
        {
            //check user existance
            var user = Membership.GetUser(UserName);
            if (user == null)
            {
                TempData["Message"] = "User Not exist.";
            }
            else
            {
                //generate password token
                var token = WebSecurity.GeneratePasswordResetToken(UserName);                
                //create url with above token
                var resetLink = "<a href='" + Url.Action("ResetPassword", "Account", new { un = UserName, rt = token }, "http") + "'>Reset Password</a>";
                
                //get user emailid
                UsersContext db = new UsersContext();
                var emailid = (from i in db.UserProfiles
                               where i.UserName == UserName
                               select i.EmailId).FirstOrDefault();
                //send mail
                string subject = "Password Reset Token";
                string body = "<b>Please find the Password Reset Token.</b><br/>The below link will be valid till 30 mins<br/>" + resetLink; //edit it
                try
                {
                    SendEMail(emailid, subject, body);
                    TempData["Message"] = "Mail Sent.";
                }
                catch (Exception ex)
                {
                    TempData["Message"] = "Error occured while sending email." + ex.Message;
                }
                //only for testing
               // TempData["Message"] = resetLink;
            }

            return View();
        }

Forgot Password View

<h2>Forgot Password</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Forgot Password Form</legend>
        <ol>
            <li>
                @Html.Label("User Name", new { @for = "UserName" })
                @Html.TextBox("UserName")
                <span style="color:red;">@TempData["Message"]</span>
            </li>
        </ol>
        <input type="submit" value="Recover" />
    </fieldset>
}

On clicking “Recover” button in Forgot password page a email notification with the link to retrieve the new password has been send.

Email notification

Code to send email is as given below. The sender password and sender email are the one from which the mail will be send to the user. Those two keys can be added in Web.config file under appSettings.

<appSettings>
   <add key="SenderEmail" value="xxx@gmail.ccom" />
   <add key="SenderPassword" value="xxxx" />
 </appSettings>

An the keys added in appSettings can be retrieved using Configuration manager.

ConfigurationManager.AppSettings["SenderPassword"]

 

private void SendEMail(string emailid, string subject, string body)
        {
            SmtpClient client = new SmtpClient();
            string SenderEmail = ConfigurationManager.AppSettings["SenderEmail"];
            string pswd = ConfigurationManager.AppSettings["SenderPassword"];
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = true;
            client.Host = "smtp.gmail.com";
            client.Port = 587;

            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(SenderEmail, pswd);
            client.UseDefaultCredentials = false;
            client.Credentials = credentials;

            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(SenderEmail);
            msg.To.Add(new MailAddress(emailid));

            msg.Subject = subject;
            msg.IsBodyHtml = true;
            msg.Body = body;

            client.Send(msg);
        }

 

The new password for the user will be displayed on clicking the “Reset password” link in the email. And also an email has been send with new password.

New password in reset link

The reset link in email will be valid till 30 mins after that the link gets expired. So the user has to reset the password before that by clicking the link.

The user can now login with the new password and change the password as per their need using Change password option.

Home page

Change password

User can now change the password using above page.