How to send forgot password link on email for reset in asp.net C#

In this article, I will show that how to send a reset password link on the mail. We need maximum time to use the code in our project so I have designed this.In this post I  have to send the mail using the Gmail, if you want to send with another domain then you can change the smtp and port number. In this first, we check the email is available in data base or not then we send a link on that email. Using that we can change/update our password.


Database (SQL Server)

Design of table:-
How to send forgot password in asp.net #

Script the creating table:-
create database [CodeSolution]

USE [CodeSolution]
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[logintable](
          [uid] [int] IDENTITY(1,1) NOT NULL,
          [email] [nvarchar](50) NULL,
          [password] [nvarchar](50) NULL,
          [password_change_status] [bit] NULL,
 CONSTRAINT [PK_logintable] PRIMARY KEY CLUSTERED
(
          [uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Data of table:-


Source code (forgotpasswordemail.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="forgotpasswordemail.aspx.cs" Inherits="forgotpasswordemail" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table align="center">
        <tr><td>Email:</td><td>
        <asp:TextBox ID="txtemail" runat="server" Width="150px"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvemail" runat="server"

                ErrorMessage="Please Enter Email" ControlToValidate="txtemail"

                ForeColor="Red"></asp:RequiredFieldValidator>

            </td></tr>

        <tr><td>&nbsp;</td><td>

            <asp:Button ID="btnsend" runat="server" Text="Send" onclick="btnsend_Click" /></td></tr>

        <tr><td colspan="2">
            <asp:Label ID="lbresult" runat="server"></asp:Label>
            </td></tr>

        </table>
    </div>
    </form>
</body>
</html>


Code behind (forgotpasswordemail.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Text;
using System.Net.Mail;
using System.Configuration;
using System.Data;

public partial class forgotpasswordemail : System.Web.UI.Page
{

    SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa;Password=12345678");

    DataTable dt = new DataTable();
    protected void page_Load(object sender, EventArgs e)
    {
   
   
    }
    protected void btnsend_Click(object sender, EventArgs e)
    {

        try
        {

            Session["email"] = txtemail.Text;

            SqlDataAdapter adp = new SqlDataAdapter("select * from logintable where email=@email", con);
            con.Open();

            adp.SelectCommand.Parameters.AddWithValue("@email", txtemail.Text);

            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {

                SqlCommand cmd = new SqlCommand("Update logintable set password_change_status=1 where email='" + txtemail.Text + "'", con);

                cmd.ExecuteNonQuery();



                SendEmail();

                lbresult.Text = "successfully sent reset link on  your mail ,please check once! Thank you.";
                con.Close();

                cmd.Dispose();

                txtemail.Text = "";

            }
            else {

                lbresult.Text = "Please enter vaild email ,please check once! Thank you.";
               
            }

        }

        catch (Exception ex)
        {

        }

    }

    // using this method we sent the mail to reciever

    private void SendEmail()
    {

        try
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("Hi,<br/> Click on below given link to Reset Your Password<br/>");
            sb.Append("<a href=http://localhost:57355/codesoluation/resetlink.aspx?username=" + GetUserEmail(txtemail.Text));
            sb.Append("&email=" + txtemail.Text + ">Click here to change your password</a><br/>");
            sb.Append("<b>Thanks</b>,<br> Code Solution <br/>");
            sb.Append("<br/><b> for more post </b> <br/>");
            sb.Append("<br/><a href=http://neerajcodesolution.blogspot.in");
            sb.Append("thanks");

            MailMessage message = new System.Net.Mail.MailMessage("neerajsrivastava@gmail.com", txtemail.Text.Trim(), "Reset Your Password", sb.ToString());

            SmtpClient smtp = new SmtpClient();

            smtp.Host = "smtp.gmail.com";

            smtp.Port = 587;

            smtp.Credentials = new System.Net.NetworkCredential("neerajsrivastava @gmail.com", "987654321");

            smtp.EnableSsl = true;

            message.IsBodyHtml = true;

            smtp.Send(message);

        }

        catch (Exception ex)
        {

        }
    }

    private string GetUserEmail(string Email)
    {
        SqlCommand cmd = new SqlCommand("select email from logintable WHERE email=@email", con);
        cmd.Parameters.AddWithValue("@email", txtemail.Text);
        string username = cmd.ExecuteScalar().ToString();
        return username;
    }
}




Source code (resetlink.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="resetlink.aspx.cs" Inherits="resetlink" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 44%;
        }
        .style2
        {
            width: 128px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
        <table class="style1" align="center">
            <tr>
                <td class="style2">
                    New Password
                </td>
                <td>
                    <asp:TextBox ID="txtpwd" runat="server" Width="158px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Confirm Password
                </td>
                <td>
                    <asp:TextBox ID="txtcofrmpwd" runat="server" Width="158px"></asp:TextBox>
                    <asp:CompareValidator ID="CompareValidatorPassword" runat="server" ControlToCompare="txtpwd"
                        ControlToValidate="txtcofrmpwd" ErrorMessage="Password does not match" Font-Names="Rockwell"
                        ForeColor="Red"></asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;
                </td>
                <td>
                    <asp:Button ID="btnsubmit" runat="server" Text="Submit" Width="156px" OnClick="btnsubmit_Click" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>



Code behind (resetlink.aspx.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;



public partial class resetlink : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        string email = Session["email"].ToString();
    }

    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        string email = Session["email"].ToString();

        SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa;Password=12345678");
        SqlCommand cmd = new SqlCommand("Update logintable set password = '"+txtpwd.Text+"'where email= '"+email+"'", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        Response.Write("<script>alert ('your password has been successfully updated')</script>");
        txtpwd.Text = "";
        txtcofrmpwd.Text = "";

    }
}

 
Out-put:-


How to send forgot password link on email for reset in asp.net C#

How to send forgot password link on email for reset in asp.net C# How to send forgot password link on email for reset in asp.net C# Reviewed by NEERAJ SRIVASTAVA on 6:52:00 PM Rating: 5

35 comments:

  1. Hey, just thought I'd leave you some friendly feedback as there are a few rather serious security vulnerabilities here you might want to address:

    - The password is stored in the database in plain text. Consider a strong password hashing algorithm, OWASP has some great guidance: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet

    - Hopefully the sa account in the connection string is just for demonstration purposes, but you might want to be clear that a DB account with "god rights" should *never* be used in a web app.

    - You've parameterised the select statement but not the update statement which just concatenates the email address into the query. As it stands, SQL injection could be used for an attacker to do ANYTHING they like to your database (i.e. delete all data). Because you're connecting with sa and attacker could also do anything they like TO ANY OTHER DATABASE!

    - You're putting the email address in session state when the reset is initiated then even though you send it as a query string parameter in the reset email, the "change password" page merely pulls it back out of session state as verification. I could enter someone else's email address then just go to http://localhost:57355/codesoluation/resetlink.aspx (without any query string) and change their password.

    Security aside, the 50 char email and password limits on the table columns will cause problems firstly because it's way too short (especially for email) and secondly because there are no max char limits on the input fields so longer strings can be entered.

    Seriously look at Microsoft's Identity implementation for this, it will help you solve many of your problems and is much easier to implement than trying to manually create it all yourself: http://www.asp.net/identity

    ReplyDelete
    Replies
    1. Email column in the table is "null" which is also a problem.

      Delete
    2. And if the SQL service is running as local admin (which it shouldn't be but which is far too common) SQL injection with an app connecting as sa can allow the attacker to compromise the OS as well.

      Delete
    3. Also, the code can give an attacker hints on which email addresses are in the DB, as it responds accordingly when entering an unknown email address.

      Delete
  2. I'M GOING TO MAIL YOU SPIDERS

    ReplyDelete
  3. If fact none of the columns in the table should be NULL. (although that's the least of the problems)

    ReplyDelete
    Replies
    1. Oh, it doesn't matter if they allow nulls. The table won't be around for long anyway. In fact, the whole database is likely to be nulled and voided in a few hours.

      OP:
      This is a diabolically bad 'code example'!

      Delete
  4. Replies
    1. And absolutely full of security problems, so probably not something you want to use without a very careful review and several changes. See earlier comments.

      Delete
  5. You can also look at the different data using different criteria such as location of the office, skill set, departments, vendors, operation expenditure versus capital and operational expenditure versus capital versus regulatory expenditure.visit this site

    ReplyDelete
  6. Thank you Neeraj very nice and easy to understand code... thank u very much....

    ReplyDelete
    Replies
    1. Hope you don't plan on using it, it's terribly insecure code.

      Delete
  7. Just implemented this code for a few clients of mine, easy copy/paste. Would highly recommend it!

    ReplyDelete
  8. Used this code to help customers reset their passwords at the bank I work at. Thank you!

    ReplyDelete
  9. This is great. Helped me a lot, has no security flaws. Will recommend it to others!

    ReplyDelete
  10. I've been fired for implementing this at my (old) company. We were hacked within the first week (we're not exactly sure when, because the attacker was able to do pretty much anything they wanted with the database, including erase our logs in the OS).

    I was too lazy to read the comments, test, or anything someone with an ounce of sense should do. I just implemented it as is, and thought I could spend the rest of my time surfing reddit and porn sites.

    Take my advise - read Troy Hunt's suggestions - and please do your homework. I've been out of work for some time now, as the breach I caused has followed me like a bad habit I just can't shake. People mock me, point fingers at me, and tell me I should die. I've exposed 1000's of emails, personal information, and some other stuff I just can't talk about (it was bad, very, very bad).

    I wish all of you better luck, and hope you use much more common sense than I did.

    Anonymous - and unemployed.

    ReplyDelete
    Replies
    1. So this is how Rosebutt was breached.

      Delete
    2. :-) Hope my little story helps someone anyway. Enjoy!

      Delete
  11. This code is beautiful. I can't see any problems a good firewall wouldn't fix. 😬

    ReplyDelete
    Replies
    1. What on earth? How would a firewall solve _any_ of the problems with this code?

      Delete
  12. Hi Gentleman I have doubt in forgot email password task. Which need to send mail with time limit and anther resend password link which need to return same link again anyone help me to get solution

    ReplyDelete
  13. I am very much pleased with the contents you have mentioned. I wanted to thank you for this great article. Solidworks 2016

    ReplyDelete
  14. Nice post bro you are a great writer this is a great software and 100% workingremovewat-2-2-9-rar-windows-7-8-10

    ReplyDelete
  15. Amazing software thanks guys loving it �� fast-and-furious-6-game

    ReplyDelete
  16. By using an email marketing solution to grow your current contact list, or create your first contact list, you can target an important market for your second-hand store. Homeowners selling their homes will help you in attaining more goods more often for your second-hand store.
    extract emails

    ReplyDelete
  17. It’s very straightforward to find out any topic on net as compared to books,
    as I found this piece of writing at this web page.

    ReplyDelete
  18. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    www.mcdonaldsgutscheine.net | www.startlr.com | www.saludlimpia.com

    ReplyDelete
  19. sir I am get error like Object reference not set to an instance of an object( for this string email = Session["email"].ToString()). why soo plz help me

    ReplyDelete

Powered by Blogger.