Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Implementing password reset link in asp.net - Part 95

Suggested Videos
Part 92 - Forms authentication against users in database table
Part 93 - Forms authentication and locking user accounts
Part 94 - Unlocking the locked user accounts



Step 1:
The first step is to design a page, that allows the user to enter their user name, for requesting, the reset of the password. Add a webform , with name "ResetPassword.aspx" to the "Registration" folder. The web.config file in this folder, allows anonymous access to all the pages without having the need to login. We discussed about having multiple web.config files and allowing anonymous access to a set of pages in Part 91 of this video series. Click here to watch Part 91, before proceeding.



Step 2:
Copy and paste the following HTML on "ResetPassword.aspx" page.
<div style="font-family:Arial">
    <table style="border: 1px solid black; width:300px">
        <tr>
            <td colspan="2">
                <b>Reset my password</b>
            </td>
        </tr>
        <tr>
            <td>
                User Name
            </td>    
            <td>
                <asp:TextBox ID="txtUserName" Width="150px" runat="server">
                </asp:TextBox>
            </td>    
        </tr>
        <tr>
            <td>
                    
            </td>    
            <td>
                <asp:Button ID="btnResetPassword" runat="server" 
                Width="150px" Text="Reset Password" onclick="btnResetPassword_Click" />
            </td>    
        </tr>
        <tr>
            <td colspan="2">
                <asp:Label ID="lblMessage" runat="server"></asp:Label>
            </td>    
        </tr>
    </table>
</div>

Step 3:
Create a table "tblResetPasswordRequests" in sql server. This table is going to store a unique GUID (Globally Unique Identifier) along with the user id, each time a user requests a password recovery. This GUID will then be passed as part of the querystring in the link to the password reset page. This link will then be emailed to the email address that is associated with the user id. When a user clicks on the link the page will look up the GUID in "tblResetPasswordRequests" table and get the user id from there allowing the user to change their password. I didn't use, UserId, as the querystring parameter, because it maybe open to abuse.

Create table tblResetPasswordRequests
(
Id UniqueIdentifier Primary key,
UserId int Foreign key references tblUsers(Id),
ResetRequestDateTime DateTime
)

Step 4:
Create a stored procedure to check if the username exists, and to insert a row into "tblResetPasswordRequests" table.
Create proc spResetPassword
@UserName nvarchar(100)
as
Begin
Declare @UserId int
Declare @Email nvarchar(100)

Select @UserId = Id, @Email = Email 
from tblUsers
where UserName = @UserName

if(@UserId IS NOT NULL)
Begin
--If username exists
Declare @GUID UniqueIdentifier
Set @GUID = NEWID()

Insert into tblResetPasswordRequests
(Id, UserId, ResetRequestDateTime)
Values(@GUID, @UserId, GETDATE())

Select 1 as ReturnCode, @GUID as UniqueId, @Email as Email
End
Else
Begin
--If username does not exist
SELECT 0 as ReturnCode, NULL as UniqueId, NULL as Email
End
End

Step 5:
Invoke the stored procedure and email the link, to the email address that is registered against the username. Copy and paste the following code in ResetPassword.aspx.cs page.

protected void btnResetPassword_Click(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("spResetPassword", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter paramUsername = new SqlParameter("@UserName", txtUserName.Text);

        cmd.Parameters.Add(paramUsername);

        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            if (Convert.ToBoolean(rdr["ReturnCode"]))
            {
                SendPasswordResetEmail(rdr["Email"].ToString(), txtUserName.Text, rdr["UniqueId"].ToString());
                lblMessage.Text = "An email with instructions to reset your password is sent to your registered email";
            }
            else 
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "Username not found!";
            }
        }
    }
}

private void SendPasswordResetEmail(string ToEmail, string UserName, string UniqueId)
{
    // MailMessage class is present is System.Net.Mail namespace
    MailMessage mailMessage = new MailMessage("YourEmail@gmail.com", ToEmail);
            
            
    // StringBuilder class is present in System.Text namespace
    StringBuilder sbEmailBody = new StringBuilder();
    sbEmailBody.Append("Dear " + UserName + ",<br/><br/>");
    sbEmailBody.Append("Please click on the following link to reset your password");
    sbEmailBody.Append("<br/>");      sbEmailBody.Append("http://localhost/WebApplication1/Registration/ChangePassword.aspx?uid=" + UniqueId);
    sbEmailBody.Append("<br/><br/>");
    sbEmailBody.Append("<b>Pragim Technologies</b>");

    mailMessage.IsBodyHtml = true;

    mailMessage.Body = sbEmailBody.ToString();
    mailMessage.Subject = "Reset Your Password";
    SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);

    smtpClient.Credentials = new System.Net.NetworkCredential()
    {
        UserName = "YourEmail@gmail.com",
        Password = "YourPassword"
    };
            
    smtpClient.EnableSsl = true;
    smtpClient.Send(mailMessage);
}

Step 6:
Add a webform with name, "ChangePassword.aspx", to "Registration" folder. Copy and paste the following HTML in the aspx page. In the next video session we will implement ChangePassword page.
<h1>Change Password Page</h1>

25 comments:

  1. Hi MR Venkat i am very much impressed by your teaching style with RJ VOICE

    YOU ARE BEST GUY ON THE INTERNET.

    ReplyDelete
  2. thank you very much ! you are just the best in the business its been two years that i am watching your videos perfect !

    ReplyDelete
    Replies
    1. Hi Joseph,

      Thank you very much for taking time to give feedback. I am really glad you found these videos useful.

      I have organised all the ASP .NET, C#, and SQL Server video tutorials in to playlists, which could be useful to you.
      http://www.youtube.com/user/kudvenkat/videos?view=1&flow=grid

      Tips to effectively use my youtube channel.
      http://www.youtube.com/watch?v=nT9uF09RMkw

      If you want to receive email alerts, when new videos are uploaded, please feel free to subscribe to my youtube channel.
      http://youtube.com/kudvenkat

      If you like these videos, please click on the THUMBS UP button below the video.

      May I ask you for a favour. I want these tutorials to be helpful for as many people as possible. Please free to share the link with your friends and family who you think would also benefit from them.

      Good Luck
      Venkat

      Delete
  3. Hi Mr Venkat,
    Thank you for your time and your willingness to share your knowledge with millions around the globe may God bless you...I will keep on learning from your blog and videos and be grateful and thankful for the opportunity that you have given me.

    ReplyDelete
  4. Thank you for the useful video.
    I want to know what is the security gap if we encrypt the userid and send it by email to the user?????

    ReplyDelete
  5. great video and very practical. thanks for sharing

    ReplyDelete
  6. I face this problem, Should I do some setting...
    The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

    ReplyDelete
    Replies
    1. the root cause of the issue is Gmail change the security setting to beef up the security. by default Access for Less secure Apps had been disabled. after i turned Access for less secure apps on. my demo goes very smooth.

      after you log into your gmail account and click on the link below to change the security setting for google account.

      https://www.google.com/settings/security/lesssecureapps


      run the code as its given

      Delete
    2. thanks Deepak pimple your reply helped

      Delete
  7. Hi Venkat,
    I get the answer already from gmail website setting
    http://www.smarterasp.net/support/kb/a1546/send-email-from-gmail-with-smtp-authentication-but-got-5_5_1-authentication-required-error.aspx
    Thank you tutorial and make me more and more better

    ReplyDelete
  8. hello sir,
    i am a student and i want to implement this iam project and i am being watching your Implementing password reset link in asp.net - Part 95 video in That i am not getting how to create this http://localhost/WebApplication1/Registration/ChangePassword.aspx?uid=
    can you pleasehelp me.

    ReplyDelete
    Replies
    1. Dear sir when I run my asp.net web site on local IIS after create self signed certificate.
      But I faced error :

      Server Error in '/app3' Application.

      The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

      Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

      Source Error:



      Line 79: smtp.UseDefaultCredentials = true;
      Line 80: smtp.EnableSsl = true;
      Line 81: smtp.Send(mailMessage);
      Line 82:
      Line 83: }


      Source File: C:\app3\app3\Registration\ResetPassword.aspx.cs Line: 81

      Stack Trace:



      [SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at]
      System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) +1840546
      System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) +46
      System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) +88
      System.Net.Mail.SmtpClient.Send(MailMessage message) +1867
      app3.Registration.ResetPassword.SendPasswordResetEmail(String ToEmail, String UserName, String UniqueId) in C:\app3\app3\Registration\ResetPassword.aspx.cs:81
      app3.Registration.ResetPassword.btnResetPassword_Click(Object sender, EventArgs e) in C:\app3\app3\Registration\ResetPassword.aspx.cs:41
      System.Web.UI.WebControls.Button.OnClick(EventArgs e) +109
      System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +108
      System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
      System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
      System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +31
      System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3454




      Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.114.0

      Delete
    2. i think u r using Gmail SMTP. For using Gmail SMTP u have to enable LESS SECURE APP IN UR GMAIL ACCOUNT SECTION.

      Delete
  9. Thank you Mr. Venkat for all your help for the last 1.5 years! I always refer to your Youtube channel to people who are asking me how to do things on a particular momment that i don't have time to explain. Furthermore, i would like to ask a silly question that bothers me for the last 3 hours and strangely i can't find the answer! Why the link doesn't appear as hyperlink ? It appears correctly but not as hyperlink..Thank you all in advance !

    ReplyDelete
  10. Hello everybody! Why does the link at my email address doesn't appear as hyperlink? The link isn't clickable. Thank you all in advance :)

    ReplyDelete
    Replies
    1. Include http:// like -> http://Your localhost Address

      Delete
    2. Thank you very much Kamran Sadiq! I already found a better way (visually) around this ,

      sbEmailBody.AppendFormat("");
      sbEmailBody.Append("Please click here to change your password !");
      sbEmailBody.Append("
      ");

      What do you think ?

      Delete
  11. dear venkat, Iam getting an error like this The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

    ReplyDelete
  12. I like your video so much. All is perfect. I love these. You are the best teacher.

    ReplyDelete
  13. Hi Venkat , I am getting the following error while running the cod and I am not getting the reason behind this :
    The namespace 'FormsAuthenticationDemo' already contains a definition for 'Registration'

    ReplyDelete
  14. hi venkat
    i got this error please tell me how it will solve


    The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

    Source Error:



    Line 78: smtpClient.EnableSsl = true;
    Line 79: smtpClient.Timeout = 20000;
    Line 80: smtpClient.Send(mailMessage);
    Line 81: }
    Line 82:


    Source File: F:\Project Work Training\Dotnet\LoginExample\LoginExample\Registration\ResetPassword.aspx.cs Line: 80

    Stack Trace:



    [SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at]
    System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) +1904286
    System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) +46
    System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) +88
    System.Net.Mail.SmtpClient.Send(MailMessage message) +1856
    LoginExample.Registration.ResetPassword.SendPasswordResetEmail(String ToEmail, String UserName, String UniqueId) in F:\Project Work Training\Dotnet\LoginExample\LoginExample\Registration\ResetPassword.aspx.cs:80
    LoginExample.Registration.ResetPassword.btnResetPassword_Click(Object sender, EventArgs e) in F:\Project Work Training\Dotnet\LoginExample\LoginExample\Registration\ResetPassword.aspx.cs:40
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9815014
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
    System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639


    ReplyDelete
  15. For Step 4 Some modification.
    Assume if the user will request another time for password reset then again data will be inserted in table then at the time of checking it will return multiple row because there is no unique constraint is there.

    what i did by some modification with your code : -

    --SP FOR RESET PASSWORD--
    ALTER proc spResetPassword
    (
    @UserName varchar(255)
    )
    as
    Begin
    Declare @UserId int
    Declare @Email varchar(255)
    Declare @Name varchar(255)

    Select @UserId = uid, @Email = email, @Name = name from UserInformation where email = @UserName

    if(@UserId IS NOT NULL)
    Begin
    --If username exists
    Declare @GUID UniqueIdentifier
    Set @GUID = NEWID()
    --If First Time Password Reset --
    Declare @isPasswordResetFirstTime int;
    SET @isPasswordResetFirstTime = (Select count(UserId) from tblResetPasswordRequests where UserId = @UserId);

    if(@isPasswordResetFirstTime = 0)
    Begin

    Insert into tblResetPasswordRequests (Id, UserId, ResetRequestDateTime) Values(@GUID, @UserId, GETDATE());
    End
    Else
    Begin
    Update tblResetPasswordRequests Set Id = @GUID, UserId=@UserId, ResetRequestDateTime=GETDATE();
    End

    Select 1 as ReturnCode, @GUID as UniqueId, @Email as Email, @Name as Name
    End
    Else
    Begin
    --If username does not exist
    SELECT 0 as ReturnCode, NULL as UniqueId, NULL as Email, NULL as Name
    End
    End

    exec spResetPassword 'admin@pradip.epizy.com';


    By the way, thanks a lot for sharing your knowledge with us.

    ReplyDelete
    Replies
    1. i want this store procedure in mysql can you help me with that

      Delete
  16. Everything is working fine but when I click on the link it doesn't redirect to change password page and I am getting page not found error

    ReplyDelete
  17. Hi Venkat,
    I have been going through this video of implementing change password page and when I execute, I get the url in my email for password reset but it appears as text and not as hyperlink.Kindly please advise.
    The below line seems not working for me.

    sbEmailBody.Append("http://localhost/WebApplication1/Registration/ChangePassword.aspx?uid=" + UniqueId);

    ReplyDelete

It would be great if you can help share these free resources