Bagikan melalui


Membership.GeneratePassword(Int32, Int32) Metode

Definisi

Menghasilkan kata sandi acak dengan panjang yang ditentukan.

public:
 static System::String ^ GeneratePassword(int length, int numberOfNonAlphanumericCharacters);
public static string GeneratePassword (int length, int numberOfNonAlphanumericCharacters);
static member GeneratePassword : int * int -> string
Public Shared Function GeneratePassword (length As Integer, numberOfNonAlphanumericCharacters As Integer) As String

Parameter

length
Int32

Jumlah karakter dalam kata sandi yang dihasilkan. Panjangnya harus antara 1 dan 128 karakter.

numberOfNonAlphanumericCharacters
Int32

Jumlah minimum karakter non-alfanumerik (seperti @, #, !, %, &, dan sebagainya) dalam kata sandi yang dihasilkan.

Mengembalikan

Kata sandi acak dengan panjang yang ditentukan.

Pengecualian

length kurang dari 1 atau lebih besar dari 128 -atau-

numberOfNonAlphanumericCharacters kurang dari 0 atau lebih besar dari length.

Contoh

Contoh kode berikut membuat pengguna keanggotaan baru dan menggunakan GeneratePassword metode untuk menginisialisasi kata sandi untuk pengguna baru ke nilai acak, yang ditampilkan kepada pengguna.

Penting

Contoh ini berisi kotak teks yang menerima input pengguna, yang merupakan potensi ancaman keamanan. Secara default, ASP.NET halaman Web memvalidasi bahwa input pengguna tidak menyertakan elemen skrip atau HTML. Untuk informasi selengkapnya, lihat Gambaran Umum Eksploitasi Skrip.

<%@ 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 CreateUser_OnClick(object sender, EventArgs args)
{
  // Generate a new 12-character password with at least 1 non-alphanumeric character.
  string password = Membership.GeneratePassword(12, 1);

  try
  {
    // Create new user.
    MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, password, 
                                                   EmailTextbox.Text);

    Msg.Text = "User <b>" + Server.HtmlEncode(UsernameTextbox.Text) + "</b> created. " +
               "Your temporary password is " + password + ".";
  }
  catch (MembershipCreateUserException e)
  {
    Msg.Text = GetErrorMessage(e.StatusCode);
  }
  catch (HttpException e)
  {
    Msg.Text = e.Message;
  }
}

public string GetErrorMessage(MembershipCreateStatus status)
{
   switch (status)
   {
      case MembershipCreateStatus.DuplicateUserName:
        return "Username already exists. Please enter a different user name.";

      case MembershipCreateStatus.DuplicateEmail:
        return "A username for that email address already exists. Please enter a different email address.";

      case MembershipCreateStatus.InvalidPassword:
        return "The password provided is invalid. Please enter a valid password value.";

      case MembershipCreateStatus.InvalidEmail:
        return "The email address provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidAnswer:
        return "The password retrieval answer provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidQuestion:
        return "The password retrieval question provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.ProviderError:
        return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

      case MembershipCreateStatus.UserRejected:
        return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

      default:
        return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
   }
}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Create User</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Create New User</h3>

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

  <table cellpadding="3" border="0">
    <tr>
      <td>Username:</td>
      <td><asp:Textbox id="UsernameTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                      ControlToValidate="UserNameTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>

    <tr>
      <td>Email Address:</td>
      <td><asp:Textbox id="EmailTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server"
                                      ControlToValidate="EmailTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>

    <tr>
      <td></td>
      <td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>
    </tr>
  </table>
</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 CreateUser_OnClick(sender As Object, args As EventArgs)
  ' Generate a new 12-character password with at least 1 non-alphanumeric character.
  Dim password As String = Membership.GeneratePassword(12, 1)

  Try
    ' Create new user.
    Dim newUser As MembershipUser = Membership.CreateUser(UsernameTextbox.Text, password, _
                                                          EmailTextbox.Text)

    Msg.Text = "User <b>" & Server.HtmlEncode(UsernameTextbox.Text) & "</b> created. " & _
               "Your temporary password is " & password & "."
  
  Catch e As MembershipCreateUserException
    Msg.Text = GetErrorMessage(e.StatusCode)
  Catch e As HttpException
    Msg.Text = e.Message
  End Try
End Sub

Public Function GetErrorMessage(status As MembershipCreateStatus) As String

   Select Case status
      Case MembershipCreateStatus.DuplicateUserName
        Return "Username already exists. Please enter a different user name."

      Case MembershipCreateStatus.DuplicateEmail
        Return "A username for that email address already exists. Please enter a different email address."

      Case MembershipCreateStatus.InvalidPassword
        Return "The password provided is invalid. Please enter a valid password value."

      Case MembershipCreateStatus.InvalidEmail
        Return "The email address provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.InvalidAnswer
        Return "The password retrieval answer provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.InvalidQuestion
        Return "The password retrieval question provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.ProviderError
        Return "The authentication provider Returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."

      Case MembershipCreateStatus.UserRejected
        Return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."

      Case Else
        Return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."
   End Select
End Function

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Create User</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Create New User</h3>

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

  <table cellpadding="3" border="0">
    <tr>
      <td>Username:</td>
      <td><asp:Textbox id="UsernameTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                      ControlToValidate="UserNameTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>

    <tr>
      <td>Email Address:</td>
      <td><asp:Textbox id="EmailTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server"
                                      ControlToValidate="EmailTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>

    <tr>
      <td></td>
      <td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>
    </tr>
  </table>
</form>

</body>
</html>

Keterangan

Metode GeneratePassword ini digunakan untuk menghasilkan kata sandi acak dan paling umum digunakan oleh ResetPassword metode yang diterapkan oleh penyedia keanggotaan untuk mengatur ulang kata sandi bagi pengguna ke kata sandi sementara baru.

Kata sandi yang dihasilkan hanya berisi karakter alfanumerik dan tanda baca berikut: !@#$%^&*()_-+=[{]};:<>|./?. Tidak ada karakter kontrol tersembunyi atau tidak dapat dicetak yang disertakan dalam kata sandi yang dihasilkan.

Catatan

Kata sandi acak yang GeneratePassword dibuat oleh metode tidak dijamin untuk meneruskan ekspresi reguler di PasswordStrengthRegularExpression properti . Namun, kata sandi acak akan memenuhi kriteria yang MinRequiredPasswordLength ditetapkan oleh properti dan numberOfNonAlphanumericCharacters parameter .

Berlaku untuk

Lihat juga