ערוך

שתף באמצעות


SqlMembershipProvider.ResetPassword(String, String) Method

Definition

Resets a user's password to a new, automatically generated password.

public:
 override System::String ^ ResetPassword(System::String ^ username, System::String ^ passwordAnswer);
public override string ResetPassword (string username, string passwordAnswer);
override this.ResetPassword : string * string -> string
Public Overrides Function ResetPassword (username As String, passwordAnswer As String) As String

Parameters

username
String

The user to reset the password for.

passwordAnswer
String

The password answer for the specified user.

Returns

The new password for the specified user.

Exceptions

passwordAnswer is invalid.

-or-

The user account is currently locked.

username is not found in the membership database.

-or-

The change password action was canceled by a subscriber to the ValidatingPassword event and the FailureInformation property was null.

-or-

An error occurred while retrieving the password from the database.

username is an empty string (""), contains a comma, or is longer than 256 characters.

-or-

passwordAnswer is an empty string, or is longer than 128 characters, and RequiresQuestionAndAnswer is true.

-or-

passwordAnswer is longer than 128 characters after encoding.

username is null.

-or-

passwordAnswer is null and RequiresQuestionAndAnswer is true.

An unhandled exception occurred.

Examples

The following code example resets a user's password and returns the new, automatically generated password.

Note

This example uses the Membership class to call the SqlMembershipProvider specified as the defaultProvider in the Web.config file. If you need to access the default provider as the type SqlMembershipProvider, you can cast the Provider property of the Membership class. To access other configured providers as a specific provider type, you can access them by their configured name with the Providers property of the Membership class and cast them as the specific provider type.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

public void Page_Load(object sender, EventArgs args)
{
  if (!Membership.EnablePasswordReset)
  {
    FormsAuthentication.RedirectToLoginPage();
  }

  Msg.Text = "";

  if (!IsPostBack)
  {
    Msg.Text = "Please enter a user name.";
  }
  else
  {
    VerifyUsername();
  }
}


public void VerifyUsername()
{
    MembershipUser user = Membership.GetUser(UsernameTextBox.Text, false);

    if (user == null)
    {
      Msg.Text = "The user name " + Server.HtmlEncode(UsernameTextBox.Text) + " was not found. Please check the value and reenter your user name.";

      QuestionLabel.Text = "";
      QuestionLabel.Enabled = false;
      AnswerTextBox.Enabled = false;
      ResetPasswordButton.Enabled = false;
    }
    else
    {
      QuestionLabel.Text = user.PasswordQuestion;
      QuestionLabel.Enabled = true;
      AnswerTextBox.Enabled = true;
      ResetPasswordButton.Enabled = true;
    }
}

public void ResetPassword_OnClick(object sender, EventArgs args)
{
  string newPassword = "";

  try
  {
    newPassword = Membership.Provider.ResetPassword(UsernameTextBox.Text, AnswerTextBox.Text);
  }
  catch (NotSupportedException e)
  {
    Msg.Text = "An error has occurred resetting your password: " + e.Message + "." +
               "Please check your values and try again.";
  }
  catch (MembershipPasswordException e)
  {
    Msg.Text = "Invalid password answer. Please reenter the answer and try again.";
    return;
  }
  catch (System.Configuration.Provider.ProviderException e)
  {
    Msg.Text = "The specified user name does not exist. Please check your value and try again.";
  }

  if (newPassword != "")
  {
    Msg.Text = "Password reset. Your new password is: " + Server.HtmlEncode(newPassword);
  }
  else
  {
    Msg.Text = "Password reset failed. Please reenter your values and try again.";
  }
}


</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Reset Password</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Reset Password</h3>

  <asp:Label id="Msg" runat="server" ForeColor="maroon" /><br />

  Username: <asp:Textbox id="UsernameTextBox" Columns="30" runat="server" AutoPostBack="true" />
            <asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                        ControlToValidate="UsernameTextBox" ForeColor="red"
                                        Display="Static" ErrorMessage="Required" /><br />

  Password Question: <b><asp:Label id="QuestionLabel" runat="server" /></b><br />

  Answer: <asp:TextBox id="AnswerTextBox" Columns="60" runat="server" Enabled="false" />
          <asp:RequiredFieldValidator id="AnswerRequiredValidator" runat="server"
                                      ControlToValidate="AnswerTextBox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" Enabled="false" /><br />

  <asp:Button id="ResetPasswordButton" Text="Reset Password" 
              OnClick="ResetPassword_OnClick" runat="server" Enabled="false" />

</form>

</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

Public Sub Page_Load(sender As Object, args As EventArgs)

  If Not Membership.EnablePasswordReset Then
    FormsAuthentication.RedirectToLoginPage()
  End If

  Msg.Text = ""

  If Not IsPostBack Then
    Msg.Text = "Please enter a user name."
  Else
    VerifyUsername()
  End If

End Sub


Public Sub VerifyUsername()

    Dim user As MembershipUser = Membership.GetUser(UsernameTextBox.Text, False)

    If user Is Nothing Then
      Msg.Text = "The user name " & Server.HtmlEncode(UsernameTextBox.Text) & " was not found. Please check the value and reenter your user name."

      QuestionLabel.Text = ""
      QuestionLabel.Enabled = False
      AnswerTextBox.Enabled = False
      ResetPasswordButton.Enabled = False
    Else
      QuestionLabel.Text = user.PasswordQuestion
      QuestionLabel.Enabled = True
      AnswerTextBox.Enabled = True
      ResetPasswordButton.Enabled = True
    End If

End Sub


Public Sub ResetPassword_OnClick(sender As Object, args As EventArgs)

  Dim newPassword As String = ""

  Try
    newPassword = Membership.Provider.ResetPassword(UsernameTextBox.Text, AnswerTextBox.Text)
  Catch e As NotSupportedException
    Msg.Text = "An error has occurred resetting your password: " & e.Message & "." & _
               "Please check your values and try again."
  Catch e As MembershipPasswordException
    Msg.Text = "Invalid password answer. Please reenter the answer and try again."
    Return
  Catch e As System.Configuration.Provider.ProviderException
    Msg.Text = "The specified user name does not exist. Please check your value and try again."
  End Try

  If newPassword <> "" Then
    Msg.Text = "Password reset. Your new password is: " & Server.HtmlEncode(newPassword)
  Else
    Msg.Text = "Password reset failed. Please reenter your values and try again."
  End If

End Sub


</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Reset Password</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Reset Password</h3>

  <asp:Label id="Msg" runat="server" ForeColor="maroon" /><br />

  Username: <asp:Textbox id="UsernameTextBox" Columns="30" runat="server" AutoPostBack="True" />
            <asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                        ControlToValidate="UsernameTextBox" ForeColor="red"
                                        Display="Static" ErrorMessage="Required" /><br />

  Password Question: <b><asp:Label id="QuestionLabel" runat="server" /></b><br />

  Answer: <asp:TextBox id="AnswerTextBox" Columns="60" runat="server" Enabled="False" />
          <asp:RequiredFieldValidator id="AnswerRequiredValidator" runat="server"
                                      ControlToValidate="AnswerTextBox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" Enabled="False" /><br />

  <asp:Button id="ResetPasswordButton" Text="Reset Password" 
              OnClick="ResetPassword_OnClick" runat="server" Enabled="False" />

</form>

</body>
</html>

Remarks

This method is called by the Membership class to reset the password for a user in the SQL Server database specified in the ASP.NET application's configuration file (Web.config) to a new, randomly generated value. The new password is returned.

Note

The random password created by the ResetPassword method is not guaranteed to pass the regular expression in the PasswordStrengthRegularExpression property. However, the random password will meet the criteria established by the MinRequiredPasswordLength and MinRequiredNonAlphanumericCharacters properties.

The ResetPassword method is most commonly used when the PasswordFormat property is set to Hashed. If a user forgets a password that is hashed, the password cannot be retrieved. However, the provider can reset the password to a new, automatically generated password if the user supplies the correct password answer.

If an incorrect password answer is supplied to the ResetPassword method, the internal counter that tracks invalid password attempts is incremented by one. This can result in the user being locked out and unable to log on until the lock status is cleared by a call to the UnlockUser method. If the correct password answer is supplied and the user is not currently locked out, then the internal counter that tracks invalid password-answer attempts is reset to zero. For more information, see the MaxInvalidPasswordAttempts and PasswordAttemptWindow properties.

You can call the ResetPassword method directly by first obtaining a reference to the SqlMembershipProvider instance from the Provider property of the Membership class. The generated password will be at least 14 characters long, or the length specified in the MinRequiredPasswordLength property, and will contain the number of non-alphanumeric characters specified in the MinRequiredNonAlphanumericCharacters property. The password is not guaranteed to pass the regular expression contained in the PasswordStrengthRegularExpression property, if one is specified.

Leading and trailing spaces are trimmed from all parameter values.

Applies to

See also