Reset and Email Forgotten Password Programmatically

With ASP.NET membership API managing website security has become easy to implement yet it is powerful to support enterprise level authentication/authorization for any application.

Today we will leverage password reset capability of membership API to reset registered user's password by generating random password and sending it to his email which is registered with the account.

Screenshot:

ASPX Code:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<style type="text/css">

#forgetPass

{

background-color:#F7F7DE;

border-color:#CCCC99;

font-size:10pt;

border-style:solid;

border-width:1px;

width:300px;

}

</style>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99"

BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"

Font-Size="10pt" DestinationPageUrl="~/Default.aspx">

<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

</asp:Login>

<br />

<div id="forgetPass">

Forgot Password?<br />

Username:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Go" />

<br />

<asp:Label ID="Label1" runat="server"></asp:Label>

</div>

</div>

</form>

</body>

</html>

 

Code Behind:

protected void Button1_Click(object sender, EventArgs e)

{

// creating MembershipUser object from username supplied in textbox

MembershipUser user = Membership.GetUser(TextBox1.Text);

// resetting user's password and returning it in string to send in an email

string newPassword= user.ResetPassword();

// creating mailmessage object for new message

MailMessage message = new MailMessage();

// adding user's email in To list of email

message.To.Add(user.Email);

// creating subject for email

message.Subject = "Your Username and Password";

// setting message's body type to html

message.IsBodyHtml = true;

// preparing email body

message.Body = @"Your pass is: "+newPassword;

// creating smtpClient object

SmtpClient smtp = new SmtpClient();

// sending email

smtp.Send(message);

// updating label to show message that email has been sent

Label1.Text = "Your new password has been sent to your registered email account!";

}

 

Thank you.

Tags: , ,

ASP.NET | Membership