ChangePassword (WebSecurity Ref)

The ChangePassword method takes 3 arguments: username, current password and new password.

Example

The following was written in ASP.NET WebPages.

C# Code

@{
    
//set general variables
string currentpassword = "";
string newpassword = "";
string confirmpassword = "";
string msg ="";
 
 
WebSecurity.RequireAuthenticatedUser();//Get the user to login first! Only logged in users can change their password
 
//proccess data on post
if (IsPost)
{
    
    currentpassword = Request["currentpassword"];
    newpassword = Request["newpassword"];
    confirmpassword = Request["confirmpassword"];
 
    //MAKE SURE FORMS ARE NOT NULL
    if (currentpassword.IsEmpty())
    {
        ModelState.AddError("currentpassword", "Please enter your current password");
    }
 
    if (newpassword.IsEmpty())
    {
       ModelState.AddError("newpassword", "Please enter a new password");
    }
    
    //MAKE SURE NEW PASSWORD AND CONFIRM PASSWORD MATCH
    if (newpassword != confirmpassword)
    {
        ModelState.AddError("confirmpassword", "Passwords do not match");
    }
 
    if (ModelState.IsValid)
    {
        try
        {
            //CHANGE PASSWORD
            if (WebSecurity.ChangePassword(WebSecurity.CurrentUserName, currentpassword, newpassword))
            {
                 msg = "Your password has been changed";
            }else
            {
                //WE HAVE A PROBLEM!
                ModelState.AddFormError("Sorry something went wrong there!");
            }
           
        }catch (Exception ex)
        {
            msg = ex.Message;
        }
    }
}
 
 
}

HTML Code

<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        
        Welcome @WebSecurity.CurrentUserName
 
        @msg
 
        @Html.ValidationSummary(true)
 
        <form method="post">
            <div>
        <label>Current Password</label>
            <input type="password" name="currentpassword"/>
            @Html.ValidationMessage("currentpassword")
                </div>
              <div>
             <label>New Password</label>
              <input type="password" name="newpassword"/>
               @Html.ValidationMessage("newpassword")
            </div>
 
              <div>
             <label>Confirm Password</label>
              <input type="password" name="confirmpassword"/>
               @Html.ValidationMessage("confirmpassword")
            </div>
 
                   <input type="submit"/>
        </form>
 
    </body>
</html>

Exceptions

System.NullReferenceException

You can only change a password for a user that is logged in. Make sure the user is logged in BEFORE changing the password.