SqlMembershipProvider.GetPassword(String, String) Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Restituisce la password per il nome utente specificato dal database di appartenenza a SQL Server.
public:
override System::String ^ GetPassword(System::String ^ username, System::String ^ passwordAnswer);
public override string GetPassword(string username, string passwordAnswer);
override this.GetPassword : string * string -> string
Public Overrides Function GetPassword (username As String, passwordAnswer As String) As String
Parametri
- username
- String
L'utente per cui recuperare la password.
- passwordAnswer
- String
Risposta della password per l'utente.
Restituisce
Password per il nome utente specificato.
Eccezioni
passwordAnswer non è valido.
oppure
L'utente di appartenenza identificato da username è bloccato.
EnablePasswordRetrieval è impostato su false.
username non viene trovato nel database di appartenenza.
oppure
Errore durante il recupero della password dal database.
Uno dei valori dei parametri supera la lunghezza massima consentita.
oppure
username è una stringa vuota (""), contiene una virgola o è più lunga di 256 caratteri.
oppure
passwordAnswer è una stringa vuota e RequiresQuestionAndAnswer è true.
oppure
passwordAnswer è maggiore di 128 caratteri.
oppure
La versione codificata di è maggiore di passwordAnswer 128 caratteri.
Esempio
Nell'esempio di codice seguente viene recuperata la password per un nome utente specificato e inviata all'utente in un messaggio di posta elettronica.
Annotazioni
La restituzione di una password in testo non crittografato tramite posta elettronica non è consigliata per i siti che richiedono un livello elevato di sicurezza. Per i siti con sicurezza elevata, è consigliabile restituire password usando la crittografia, ad esempio SSL.
Annotazioni
In questo esempio viene chiamato l'oggetto SqlMembershipProvider specificato come defaultProvider nel file Web.config usando la Membership classe . Se è necessario accedere al provider predefinito come tipo SqlMembershipProvider, è possibile eseguire il cast della Provider proprietà della Membership classe . Per accedere ad altri provider configurati come tipo di provider specifico, è possibile accedervi tramite il nome configurato con la proprietà della classe ed eseguirne il ProvidersMembership cast come tipo di provider specifico.
<%@ 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>
Commenti
Questo metodo viene chiamato dalla MembershipUser classe per recuperare la password per un utente dal database di SQL Server specificato nel file di configurazione dell'applicazione ASP.NET (Web.config).
Se viene fornita una risposta errata alla password al GetPassword metodo , il contatore interno che tiene traccia dei tentativi di risposta password non validi viene incrementato di uno. Ciò può comportare il blocco dell'utente e l'impossibilità di accedere fino a quando lo stato del blocco non viene cancellato da una chiamata al UnlockUser metodo . Se viene fornita la risposta password corretta e l'utente non è attualmente bloccato, il contatore interno che tiene traccia dei tentativi di risposta password non validi viene reimpostato su zero. Per altre informazioni, vedere le MaxInvalidPasswordAttempts proprietà e PasswordAttemptWindow .
È possibile chiamare direttamente il GetPassword metodo ottenendo prima un riferimento all'istanza SqlMembershipProvider tramite la Provider proprietà della Membership classe .
Se la PasswordFormat proprietà è impostata su Hashed, il GetPassword metodo non può recuperare la password. Le password con hash sono crittografate unidirezionale e non possono essere decrittografate. Se la PasswordFormat proprietà è impostata su Hashede EnablePasswordRetrieval è impostata su true, viene generata un'eccezione ProviderException quando il provider viene inizializzato.
Gli spazi iniziali e finali vengono eliminati da tutti i valori dei parametri.