Link to home
Start Free TrialLog in
Avatar of Brian
BrianFlag for United States of America

asked on

Forgot Password

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

Avatar of Bardobrave
Bardobrave
Flag of Spain image

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.

Avatar of Brian

ASKER

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?
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.
Avatar of Brian

ASKER

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.
Avatar of Brian

ASKER

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

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.
Avatar of Brian

ASKER

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?
ASKER CERTIFIED SOLUTION
Avatar of Bardobrave
Bardobrave
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial