Search code examples
c#asp.net-mvcforms-authentication

How to find OldPassword to let the user change it


I'm working on an intranet, I've just added a feature on the user's profile to change his password.

As you can see with the following controller :

[HttpPost]        
    public ActionResult ChangePassword(Employee objToEdit, FormCollection form, LocalPasswordModel model) // Find how to obtain "OldPassword" from AccountModel
    {
        objToEdit.Login = User.Identity.Name;
        string name = objToEdit.FirstName;
        string pwd = form["NewPassword"];
        string confirm = form["ConfirmPassword"];

        if (_service.Edit_password(objToEdit, pwd, confirm)) // Checks if NewPassword and ConfirmPassword are the same, and does some syntax checking
        {
            bool changePasswordSucceeded;
            try
            {
                changePasswordSucceeded = WebSecurity.ResetPassword(WebSecurity.GeneratePasswordResetToken(objToEdit.Login), pwd); // Seems to work                   
            }
            catch (Exception)
            {
                changePasswordSucceeded = false;
            }

            if (changePasswordSucceeded)
            {
                return RedirectToAction("Index", new { Message = CRAWebSiteMVC.Controllers.AccountController.ManageMessageId.ChangePasswordSuccess });
            }
            else
            {
                ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
            }
            return new RedirectResult(Url.Action("Index"));
        }
        return View();
    }

So far, the user just needs to input a New password and a confirmation password. I wish to add a "Enter your current Password" feature but I can't find a way to retrieve the user's current password !

The user profile DB does not contain a Password column anymore and I use Form authentication if that's of any help.

EDIT: Thank you for your help, to solve my problem I simply replaced the ResetPassword line by the following :

changePasswordSucceeded = WebSecurity.ChangePassword(objToEdit.Login, current, pwd);

If it fails, it directly displays the error message that the current password is wrong.


Solution

  • You can't !

    That's actually a security feature. You should never store a password in plain text.

    The good thing is, you don't need to do the comparison yourself:

    Instead, use something like ValidateUser to let the Membership Provider validate the provided password. Behind the scenes, this method will hash the password and compare it with the hashed version contained in the database.

    EDIT:

    Also, note that since you are using the WebSecurity class, there is a method, ChangePassword that accepts the current password. It seems that method will check the current password matches the specified currentPassword parameter. Maybe you should use this one instead of ResetPassword