Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to implement forgot password functionality in ASP.NET

Author: Alanna Kremer
Download Source Code : 1444_ForgotPassword.zip

In this article, we will see how we can implement forgot password functionality on a login page in ASP.NET.

This article is the continuation of my previous two articles on DevASP.NET. These articles are how to create a signup page and how to create a login page. In the login page, most of the times you can see a forgot password link. This link redirects you to another page where you can see the functionality of forgot password is implemented. We have learned to create a signup page and a login page in previous articles now we need to learn forgot password functionality. The purpose of this article is to explain how this functionality is implemented.

There are different methods and approaches to implement forgot password functionality. No matter which method or approach you want to use, the basic idea is simple. You just need to ask and check the credentials of the user, check the database for password against that user id, username or email and send an email of the password to his/her email account. You can add lots of restrictions, constraints like security questions and fix number of attempts for a user when you are implementing forgot password functionality but I am going to make it simple here.
 
We have seen on some login pages that they use username and password to login but we have used email and password. We also know that built-in controls to create user, login user and password recovery are also available in Visual Studio toolbox but we have used our own functionality so we are choosing the same track in this article as well. We are going to use same table which we have used in signup and login pages.
 
Table Name: Account
Column Names: AccountID, FirstName, LastName, Email, Password, ConfirmPassword and CreateDate
 
Add a link of Forgot Password in Login page and redirects it to retrieve password page
 
Add code below in aspx page
<table>
       <tr>
            <td colspan="3" style="height: 21px; text-align: left">
                <span style="font-size: 12pt">Please provide following information to retrieve password
              </span></td>
       </tr>
        <tr>
            <td style="width: 100px">
                <asp:Label ID="lblFirstName" runat="server" Text="First Name:" Width="80px"></asp:Label>
            </td>
            <td style="width: 116px">
                <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
            </td>
            <td style="width: 100px">
               <asp:RequiredFieldValidator ID="FirstNameRequiredFieldValidator" runat="server"
                 ForeColor="Red" ControlToValidate="txtFirstName" Display="Dynamic"
                 ErrorMessage="First Name Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td style="width: 100px">
                <asp:Label ID="lblLastName" runat="server" Text="Last Name:" Width="80px"></asp:Label>
            </td>
            <td style="width: 116px">
                <asp:TextBox ID="txtLastName" runat="server" ></asp:TextBox>
            </td>
            <td style="width: 100px">
                 <asp:RequiredFieldValidator ID="LastNameRequiredFieldValidator" runat="server"
                   ForeColor="Red" ControlToValidate="txtLastName" Display="Dynamic"
                   ErrorMessage="Last Name Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
            </td>
        tr>
        <tr>
            <td style="width: 71px" valign="top">
                     <asp:Label ID="lblEmail" runat="server" Text="Email:">asp:Label>td>
            <td style="width: 150px; text-align: left;" valign="top">
                <asp:TextBox ID="txtEmail" runat="server" Width="225px" >asp:TextBox>td>
            <td style="width: 37px" valign="top">
                    <asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server"
                     ControlToValidate="txtEmail" Display="Dynamic" ForeColor="Red"
                     ErrorMessage="Email Required" SetFocusOnError="True</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server"
                       ForeColor="Red" ControlToValidate="txtEmail" Display="Dynamic"
                       ErrorMessage="Provide Valid Email Address"
                               ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*
                    </asp:RegularExpressionValidator></td>
        </tr>
        <tr>
            <td style="width: 71px; height: 27px;"></td>
            <td style="width: 178px; text-align: right; height: 27px;">
                <asp:Button ID="btnRetrievePassword" runat="server" Style="position: relative"
                     Text="Retrieve Password" onclick="btnRetrievePassword_Click" /></td>
            <td style="width: 37px; height: 27px; text-align: right">
            </td>
        </tr>
        <tr>
            <td colspan="3" style="height: 27px; text-align: center">
                <asp:ValidationSummary ID="ValidationSummary" ForeColor="Red" runat="server" />
            </td>
        </tr>
</table>
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
 
Write below stored procedure to get password from database
 
CREATE PROCEDURE dbo.GetPassword
       (
       @FirstName           varchar(100),
       @LastName           varchar(100),
       @Email                  varchar(100)
       )
AS    
BEGIN
 
  DECLARE @RecordCount INT
 
  SELECT Password
  FROM     Account
 WHERE  FirstName = @FirstName
 AND        LastName = @LastName
 AND       Email = @Email
 
 
END
 
Add following namespaces in your code behind file
 
C#
 
using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;
using System.Net;
 
VB.NET
 
Imports System.Data.SqlClient
Imports System.Data
Imports System.Net.Mail
Imports System.Net
 
Now write code below in code behind file
 
C#
 
protected void btnRetrievePassword_Click(object sender, EventArgs e)
{
    string password = GetPassword(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim());
 
    if (password != "")
    {
        try
        {
            SendEmail(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim(), password);
            lblMessage.Text = "Your password is sent to your email";
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Sorry! an error occured while sending email, please try again";
        } 
    }
    else
    {
        lblMessage.Text = "Please provide correct information";
    }
}
 
public string GetPassword(string firstName, string lastName, string email)
{
    string password = "";
 
    string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";
    SqlConnection conn = new SqlConnection(connstring);
 
    SqlCommand cmd = new SqlCommand("GetPassword", conn);
    cmd.CommandType = CommandType.StoredProcedure;
 
    cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = firstName;
    cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 100).Value = lastName;
    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;
 
    try
    {
        conn.Open();
        cmd.ExecuteNonQuery();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adapter.Fill(dt);

 

        foreach (DataRow dr in dt.Rows)
        {
            if (dr["Password"] != DBNull.Value)
            {
                password = dr["Password"].ToString();
            }
            break;
        }
    }
    catch (Exception ex)
    {
        password = "";
    }
    conn.Close();
    return password;
}
 
public void SendEmail(string firstname, string lastname, string email, string password)
{
    MailMessage emailMessage = new MailMessage("YourEmail@gmail.com", email);
    emailMessage.Subject = "Password Recovery";
 
    string body = "Dear " + firstname + " " + lastname + ",<br/><br/>";
    body += "Here is your password '" + password + "'. <br/>";
    body += "Please login using your email and password. <br/><br/>";
    body += "Thank You";
 
    emailMessage.Body = body;
    emailMessage.IsBodyHtml = true;
 
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    NetworkCredential NetworkCred = new NetworkCredential("YourEmail", "YourPassword");
    client.UseDefaultCredentials = true;
    client.Credentials = NetworkCred;
    client.Port = 587;
    client.Send(emailMessage);
}
 
VB.NET
 
 Protected Sub btnRetrievePassword_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRetrievePassword.Click
    Dim password As String = GetPassword(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim())
 
    If password <> "" Then
        Try
            SendEmail(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim(), password)
            lblMessage.Text = "Your password is sent to your email"
        Catch ex As Exception
            lblMessage.Text = "Sorry! an error occured while sending email, please try again"
        End Try
    Else
        lblMessage.Text = "Please provide correct information"
    End If
End Sub
 
Public Function GetPassword(ByVal firstName As String, ByVal lastName As String, ByVal email As String) As String
    Dim password As String = ""
 
    Dim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"
    Dim conn As New SqlConnection(connstring)
 
    Dim cmd As New SqlCommand("GetPassword", conn)
    cmd.CommandType = CommandType.StoredProcedure
 
    cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = firstName
    cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 100).Value = lastName
    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email
 
    Try
        conn.Open()
        cmd.ExecuteNonQuery()
        Dim adapter As New SqlDataAdapter(cmd)
        Dim dt As New DataTable()
        adapter.Fill(dt)

 

        For Each dr As DataRow In dt.Rows
           If IsDBNull(dr("Password") = False) Then
                password = dr("Password").ToString()
           End If
           Exit For
        Next
    Catch ex As Exception
        password = ""
    End Try
    conn.Close()
    Return password
End Function
 
Public Sub SendEmail(ByVal firstname As String, ByVal lastname As String, ByVal email As String, ByVal password As String)
    Dim emailMessage As New MailMessage("YourEmail@gmail.com", email)
    emailMessage.Subject = "Password Recovery"
 
    Dim body As String = "Dear " & firstname & " " & lastname & ",<br/><br/>"
    body += "Here is your password '" & password & "'. <br/>"
    body += "Please login using your email and password. <br/><br/>"
    body += "Thank You"
 
    emailMessage.Body = body
    emailMessage.IsBodyHtml = True
 
    Dim client As New SmtpClient()
    client.Host = "smtp.gmail.com"
    client.EnableSsl = True
    Dim NetworkCred As New NetworkCredential("YourEmail", "YourPassword")
    client.UseDefaultCredentials = True
    client.Credentials = NetworkCred
    client.Port = 587
    client.Send(emailMessage)
End Sub

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to import Gmail contacts in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net