SqlMembershipProvider.ResetPassword(String, String) Metoda

Definicja

Resetuje hasło użytkownika do nowego, automatycznie wygenerowanego hasła.

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

Parametry

username
String

Użytkownik, aby zresetować hasło.

passwordAnswer
String

Odpowiedź na hasło dla określonego użytkownika.

Zwraca

Nowe hasło dla określonego użytkownika.

Wyjątki

Nazwa passwordAnswer jest niepoprawna.

-lub-

Konto użytkownika jest obecnie zablokowane.

EnablePasswordReset parametr jest ustawiony na falsewartość .

username nie można odnaleźć w bazie danych członkostwa.

-lub-

Akcja zmiany hasła została anulowana przez subskrybenta zdarzenia ValidatingPassword , a FailureInformation właściwość to null.

-lub-

Wystąpił błąd podczas pobierania hasła z bazy danych.

username jest pustym ciągiem (""), zawiera przecinek lub jest dłuższy niż 256 znaków.

-lub-

passwordAnswer jest pustym ciągiem lub jest dłuższy niż 128 znaków i RequiresQuestionAndAnswer ma wartość true.

-lub-

passwordAnswer po kodowaniu jest dłuższy niż 128 znaków.

username to null.

-lub-

passwordAnswer to null i RequiresQuestionAndAnswer ma wartość true.

Wystąpił nieobsługiwany wyjątek.

Przykłady

Poniższy przykład kodu resetuje hasło użytkownika i zwraca nowe, automatycznie wygenerowane hasło.

Uwaga

W tym przykładzie użyto Membership klasy , aby wywołać SqlMembershipProvider element określony jako defaultProvider w pliku Web.config. Jeśli musisz uzyskać dostęp do domyślnego dostawcy jako typu SqlMembershipProvider, możesz rzutować Provider właściwość Membership klasy . Aby uzyskać dostęp do innych skonfigurowanych dostawców jako określony typ dostawcy, możesz uzyskać do nich dostęp za pomocą ich skonfigurowanej nazwy z Providers właściwością Membership klasy i rzutować je jako określony typ dostawcy.

<%@ 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>

Uwagi

Ta metoda jest wywoływana przez Membership klasę w celu zresetowania hasła użytkownika w bazie danych SQL Server określonej w pliku konfiguracji aplikacji ASP.NET (Web.config) do nowej, losowo wygenerowanej wartości. Zostanie zwrócone nowe hasło.

Uwaga

Losowe hasło utworzone przez metodę ResetPassword nie gwarantuje przekazania wyrażenia regularnego PasswordStrengthRegularExpression we właściwości . Jednak losowe hasło będzie spełniać kryteria ustanowione przez MinRequiredPasswordLength właściwości i MinRequiredNonAlphanumericCharacters .

Metoda ResetPassword jest najczęściej używana, gdy właściwość jest ustawiona PasswordFormat na Hashedwartość . Jeśli użytkownik zapomni hasła, które jest skrótem, nie można pobrać hasła. Jednak dostawca może zresetować hasło do nowego, automatycznie wygenerowanego hasła, jeśli użytkownik dostarczy prawidłową odpowiedź na hasło.

Jeśli do metody zostanie podana ResetPassword niepoprawna odpowiedź na hasło, wewnętrzny licznik śledzący nieprawidłowe próby hasła jest zwiększany o jeden. Może to spowodować zablokowanie użytkownika i nie można się zalogować, dopóki stan blokady nie zostanie wyczyszczone przez wywołanie UnlockUser metody . Jeśli podano poprawną odpowiedź na hasło i użytkownik nie jest obecnie zablokowany, wewnętrzny licznik śledzący nieprawidłowe próby odpowiedzi na hasło jest resetowany do zera. Aby uzyskać więcej informacji, zobacz właściwości MaxInvalidPasswordAttempts i PasswordAttemptWindow.

Metodę ResetPassword można wywołać bezpośrednio, najpierw uzyskując odwołanie do SqlMembershipProvider wystąpienia z Provider właściwości Membership klasy . Wygenerowane hasło będzie mieć długość co najmniej 14 znaków lub długość określoną we MinRequiredPasswordLength właściwości i będzie zawierać liczbę znaków innych niż alfanumeryczne określone we MinRequiredNonAlphanumericCharacters właściwości . Hasło nie ma gwarancji przekazania wyrażenia regularnego zawartego PasswordStrengthRegularExpression we właściwości , jeśli zostało określone.

Spacje wiodące i końcowe są przycinane ze wszystkich wartości parametrów.

Dotyczy

Zobacz też