Membership.EnablePasswordRetrieval Propriedade
Definição
Obtém um valor que indica se o provedor de associação atual foi configurado para permitir que os usuários recuperem suas senhas.Gets a value indicating whether the current membership provider is configured to allow users to retrieve their passwords.
public:
static property bool EnablePasswordRetrieval { bool get(); };
public static bool EnablePasswordRetrieval { get; }
member this.EnablePasswordRetrieval : bool
Public Shared ReadOnly Property EnablePasswordRetrieval As Boolean
Valor da propriedade
true se o provedor de associação dá suporte à recuperação de senha; caso contrário, false.true if the membership provider supports password retrieval; otherwise, false.
Exemplos
O exemplo de código a seguir mostra o elemento membership na system.web seção do arquivo Web.config para um aplicativo ASP.net.The following code example shows the membership element in the system.web section of the Web.config file for an ASP.NET application. Ele especifica que o aplicativo usa uma instância do SqlMembershipProvider e habilita a recuperação de senha.It specifies that the application use an instance of the SqlMembershipProvider and enables password retrieval.
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">
<providers>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="true"
enablePasswordReset="false"
requiresQuestionAndAnswer="false"
passwordFormat="Encrypted"
applicationName="MyApplication" />
</providers>
</membership>
O exemplo de código a seguir primeiro verifica se EnablePasswordRetrieval é true , em seguida, recupera a senha para um nome de usuário especificado e a envia para o endereço de email do usuário especificado.The following code example first verifies that EnablePasswordRetrieval is true, then retrieves the password for a specified user name and sends it to the email address for the specified user.
Importante
Retornar uma senha em texto não criptografado usando email não é recomendado para sites que exigem um alto nível de segurança.Returning a password in clear text using email is not recommended for sites that require a high level of security. Para sites de alta segurança, recomendamos que você retorne senhas usando criptografia, como SSL.For high-security sites, we recommend that you return passwords using encryption, such as SSL.
Este exemplo inclui uma caixa de texto que aceita a entrada do usuário, que é uma possível ameaça à segurança.This example includes a text box that accepts user input, which is a potential security threat. Por padrão, as páginas da Web do ASP.NET validam que a entrada do usuário não inclui elementos de script ou HTML.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Para obter mais informações, consulte Visão geral de explorações de script.For more information, see Script Exploits Overview.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Net.Mail" %>
<!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.EnablePasswordRetrieval)
{
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 re-enter.";
QuestionLabel.Text = "";
QuestionLabel.Enabled = false;
AnswerTextBox.Enabled = false;
EmailPasswordButton.Enabled = false;
}
else
{
QuestionLabel.Text = user.PasswordQuestion;
QuestionLabel.Enabled = true;
AnswerTextBox.Enabled = true;
EmailPasswordButton.Enabled = true;
}
}
public void EmailPassword_OnClick(object sender, EventArgs args)
{
// Note: Returning a password in clear text using email is not recommended for
// sites that require a high level of security.
try
{
string password = Membership.Provider.GetPassword(UsernameTextBox.Text, AnswerTextBox.Text);
MembershipUser u = Membership.GetUser(UsernameTextBox.Text);
EmailPassword(u.Email, password);
Msg.Text = "Your password was sent via email.";
}
catch (MembershipPasswordException e)
{
Msg.Text = "The password answer is incorrect. Please check the value and try again.";
}
catch (System.Configuration.Provider.ProviderException e)
{
Msg.Text = "An error occurred retrieving your password. Please check your values " +
"and try again.";
}
}
private void EmailPassword(string email, string password)
{
try
{
MailMessage Message = new MailMessage("administrator", email);
Message.Subject = "Your Password";
Message.Body = "Your password is: " + Server.HtmlEncode(password);
SmtpClient SmtpMail = new SmtpClient("SMTPSERVER");
SmtpMail.Send(Message);
}
catch
{
Msg.Text = "An exception occurred while sending your password. Please try again.";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Retrieve Password</title>
</head>
<body>
<form id="form1" runat="server">
<h3>Retrieve 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="EmailPasswordButton" Text="Email My Password"
OnClick="EmailPassword_OnClick" runat="server" Enabled="false" />
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Net.Mail" %>
<!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(ByVal sender As Object, ByVal args As EventArgs)
If Not Membership.EnablePasswordRetrieval Then
FormsAuthentication.RedirectToLoginPage()
End If
Msg.Text = ""
If Not IsPostBack Then
Msg.Text = "Please enter a user name."
Else
VerifyUsername()
End If
End Sub
Private 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 re-enter."
QuestionLabel.Text = ""
QuestionLabel.Enabled = False
AnswerTextBox.Enabled = False
EmailPasswordButton.Enabled = False
Else
QuestionLabel.Text = user.PasswordQuestion
QuestionLabel.Enabled = True
AnswerTextBox.Enabled = True
EmailPasswordButton.Enabled = True
End If
End Sub
Public Sub EmailPassword_OnClick(ByVal sender As Object, ByVal args As EventArgs)
' Note: Returning a password in clear text using email is not recommended for
' sites that require a high level of security.
Try
Dim password As String = Membership.Provider.GetPassword(UsernameTextBox.Text, AnswerTextBox.Text)
Dim u As MembershipUser = Membership.GetUser(UsernameTextBox.Text)
EmailPassword(u.Email, password)
Msg.Text = "Your password was sent via email."
Catch e As MembershipPasswordException
Msg.Text = "The password answer is incorrect. Please check the value and try again."
Catch e As System.Configuration.Provider.ProviderException
Msg.Text = "An error occurred retrieving your password. Please check your values " & _
"and try again."
End Try
End Sub
Private Sub EmailPassword(ByVal email As String, ByVal password As String)
Try
Dim Message As MailMessage = New MailMessage("administrator", email)
Message.Subject = "Your Password"
Message.Body = "Your password is: " & Server.HtmlEncode(password)
Dim SmtpMail As SmtpClient = New SmtpClient("SMTPSERVER")
SmtpMail.Send(Message)
Catch
Msg.Text = "An exception occurred while sending your password. Please try again."
End Try
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Retrieve Password</title>
</head>
<body>
<form id="form1" runat="server">
<h3>
Retrieve 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="EmailPasswordButton" Text="Email My Password" OnClick="EmailPassword_OnClick"
runat="server" Enabled="False" />
</form>
</body>
</html>
Comentários
Se EnablePasswordRetrieval for false , o provedor de associação subjacente poderá lançar um HttpException .If EnablePasswordRetrieval is false, the underlying membership provider may throw a HttpException.
Os provedores incluídos com o .NET Framework oferecem suporte a vários formatos de senha para aprimorar a segurança de senha.The providers that are included with the .NET Framework support multiple password formats to enhance password security. Se o formato de senha for definido como Hashed , os usuários não poderão recuperar sua senha existente do banco de dados.If the password format is set to Hashed, then users will not be able to retrieve their existing password from the database. O Hashed formato de senha fornece codificação unidirecional de valores de senha.The Hashed password format provides one-way encoding of password values. As senhas são "com hash" e comparadas com os valores armazenados no banco de dados para autenticação.Passwords are "hashed" and compared to values stored in the database for authentication. Valores "com hash" não podem ser codificados para recuperar o valor da senha original."Hashed" values cannot be un-encoded to retrieve the original password value. Para obter mais informações, consulte MembershipPasswordFormat.For more information, see MembershipPasswordFormat.