?
Solved

Forgot Password

Posted on 2011-10-19
8
Medium Priority
?
277 Views
Last Modified: 2012-05-12
Hello Experts,

I created a custom ASP.NET Login Form and would like to know the best way to create something that will allow the user to retrieve his/her password from the database if they forgot it. Please see my attached Custom Login CodeBehind. I would like the know the best way/method to retrieve the users password if they forgot.


LOGIN CODEBEHIND:

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class programinfo_ghap_login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btn_ProgramInfoSignIn_Click(object sender, EventArgs e)
    {
        //Retrieve the guid from db
        string guid = String.Empty;

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthCourses"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "HealthCourses_LoginPassSalt";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@users_username", SqlDbType.VarChar).Value = txtUserName.Text;

            DataTable dtGuid = new DataTable();

            SqlDataAdapter adp = new SqlDataAdapter();
            adp.SelectCommand = cmd;
            adp.Fill(dtGuid);

            if (dtGuid != null && dtGuid.Rows.Count > 0)
            {
                guid = dtGuid.Rows[0]["users_password_salt"].ToString();

                SqlCommand cmdClientLogin = new SqlCommand();
                cmdClientLogin.CommandText = "HealthCourses_Login";
                cmdClientLogin.CommandType = CommandType.StoredProcedure;
                cmdClientLogin.Connection = conn;

                cmdClientLogin.Parameters.AddWithValue("@users_username", SqlDbType.VarChar).Value = txtUserName.Text;
                cmdClientLogin.Parameters.AddWithValue("@users_password", SqlDbType.VarChar).Value = SHA512_HASH.ComputeSHA512Hash(txtPassword.Text + guid);

                conn.Open();

                SqlDataReader rdr = cmdClientLogin.ExecuteReader();

                if (rdr.HasRows && rdr.Read())
                {
                    rdr.Close();
                    conn.Close();
                    Session["UserNameSessionID"] = txtUserName.Text;
                    FormsAuthentication.RedirectFromLoginPage(txtPassword.Text, false);
                }
            }

            else
            {
                lblSignInError.Text = "Invalid Credentials!";
            }
        }
    }
}

Open in new window

0
Comment
Question by:asp_net2
  • 4
  • 4
8 Comments
 
LVL 19

Expert Comment

by:Bardobrave
ID: 36993820
Best practice usually is to ask user to retrieve password and send it to a mail address it used to sign up. This way you only need to use a link, ask user to introduce his username and send the email.

If someone is trying to impersonate your user, it won't be able to get the password although he also has cracked the mail account and your user has used that email account to sign up into your web.

0
 
LVL 4

Author Comment

by:asp_net2
ID: 36994315
Hi Bardobrave,

Could you explain what I should do in steps for me? Example: What should happen after user clicks on "Forgot Password"? How does user retrieve password that may be hashed and salted?
0
 
LVL 19

Expert Comment

by:Bardobrave
ID: 36994379
When user clicks on forgot my password you prompt him to a form where you ask him for it's username.

When this form is sent you send a mail to the email address associated to this username with the password unencrypted.

If you don't want to send the password unencrypted you can allow user to change it's password from the email, instead of sending the password to him. Then you can put a link to the change password app into the mail, to ensure that no fraudulent users can access to it. The key here is to force the use of the email associated to ensure the authentication of the user asking for the password retrieval/change.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Author Comment

by:asp_net2
ID: 36994469
Ok, stand by please. I'm going to create something quickly that will have the user enter his/her username and then email unencrypted password to user using the email assocaited to username like you said.
0
 
LVL 4

Author Comment

by:asp_net2
ID: 36994823
Hi Bardobrave,

Sorry to ask you this but I'm stuck and not sure how to check against value being entered into txtUsername.Text. I would assume that I need to determine that this value is present in the DB first before emailing and if so then execute/send the email. But if value entered (username) is not in the DB then do not execute/send the email but display message that username does not exist.




using System;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class programinfo_ghap_forgotpassword : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btn_ForgotPassword_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthCourses"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@users_username", SqlDbType.VarChar).Value = txtUsername.Text;

            try
            {
                conn.Open();

                SmtpClient smtpClient = new SmtpClient();
                MailMessage message = new MailMessage();

                // Prepare email address
                MailAddress fromAddress = new MailAddress(HttpUtility.HtmlEncode(txtYourEmail.Text));
                MailAddress toAddress = new MailAddress("retrievepwd@test.org", "Password Retrieval");
                //Dim ccAddress As New MailAddress("first.last@nndsonline.org", "First Last")
                message.From = fromAddress;
                message.To.Add(toAddress);
                //message.CC.Add(ccAddress)
                message.Subject = HttpUtility.HtmlEncode(txtYourEmail.Text);
                //message.Subject = "NNDS - Polycom Conferencing Form";
                message.IsBodyHtml = true;
                message.Body = "<html><head><title>" + "</title></head><body>" + "<p>" + "<span style=\"font-size: 16px; color: #780028; font-family: Arial\"><p><b>Password Retrieval:</b></p></span>" + "<br />" + "<span style=\"font-size: 14px; color: #780028; font-family: Arial\"><b>Username:&nbsp;</b><font face='arial' color='#666666'>" + HttpUtility.HtmlEncode(txtOrgName.Text) + "</font></span><br />" + "<span style=\"font-size: 14px; color: #780028; font-family: Arial\"><b>Password:&nbsp;</b><font face='arial' color='#666666'>" + HttpUtility.HtmlEncode(txtYourFullName.Text) + "</font></span><br />" + "</body></html>";

                smtpClient.Host = "mail.test.org";
                smtpClient.Send(message);     
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            finally
            {
                conn.Close();
            }
        }
    }
}

Open in new window

0
 
LVL 19

Expert Comment

by:Bardobrave
ID: 36998015
Of course, if the email isn't on the database you return user to a message. You don't want to spam mails to email adresses out of your registered users.
0
 
LVL 4

Author Comment

by:asp_net2
ID: 36999384
Bardobrave,

What do you suggest then? I mean, if I cannot return password to user via email which I understand now that it's a security risk and if you now saying "You don't want to spam mails to email address" then what other options are there for the user to change his/her password?
0
 
LVL 19

Accepted Solution

by:
Bardobrave earned 2000 total points
ID: 36999654
Maybe I don't explained myself clearly.

When a user states a valid email you are not spamming. You are sending a legitimate email as your user is asking for it. You can add a link to the mail to allow your users to warn you when the mail arrives to their inbox without being asked by them, so you can track malicious impersonations.

The fact of sending an email with the password unencrypted doesn't have to be necessarily a security risk, as you'll never send on the mail both username and password and your user will be the only one who read the mail.

Sure, some bad hacker can hack the email address of your user, state that this address has been used on your site to sign up, somehow make some social engineering to guess your user username and retrieve the password in this way. But this was a problem born on a previous hack on an email account, wich you cannot control.

Check google's, linkedIn's, twitter's and facebook's retrieve password behaviours, I'm pretty sure they will be similar to this.
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question