Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Implementing change password page in asp.net - Part 96

Suggested Videos
Part 93 - Forms authentication and locking user accounts
Part 94 - Unlocking the locked user accounts
Part 95 - Implementing password reset link

In this video we will discuss about, implementing change password page in asp.net. When the user clicks on password reset link, the user lands on ChangePassword.aspx page. In Part 95, we discussed about, generating and emailing the password reset link. The password reset link looks as shown below.
http://localhost/WebApplication1/Registration/ChangePassword.aspx?uid=c19b3a4a-7fd2-47dc-9c2a-be541daed8fa



Notice that, ChangePassword.aspx page has a query string "uid". This GUID(Globally unique identifier), is used to look up UserID, for whom the password needs to be changed. After updating the password, delete the row from "tblResetPasswordRequests", so the link becomes invalid after the user has changed his/her password. Since, user id's are integers, they may be open for abuse as it is very easy to use random integers as query string values, to change other users password. 







Stored Procedure to check, if the password reset link, is a valid link.
Create Proc spIsPasswordResetLinkValid 
@GUID uniqueidentifier
as
Begin
Declare @UserId int

If(Exists(Select UserId from tblResetPasswordRequests where Id = @GUID))
Begin
Select 1 as IsValidPasswordResetLink
End
Else
Begin
Select 0 as IsValidPasswordResetLink
End
End

Stored Procedure to change password
Create Proc spChangePassword
@GUID uniqueidentifier,
@Password nvarchar(100)
as
Begin
Declare @UserId int

Select @UserId = UserId 
from tblResetPasswordRequests
where Id= @GUID

if(@UserId is null)
Begin
-- If UserId does not exist
Select 0 as IsPasswordChanged
End
Else
Begin
-- If UserId exists, Update with new password
Update tblUsers set
[Password] = @Password
where Id = @UserId

-- Delete the password reset request row 
Delete from tblResetPasswordRequests
where Id = @GUID

Select 1 as IsPasswordChanged
End
End

ChangePassword.aspx.cs page code
<div style="font-family: Arial">
<table style="border: 1px solid black">
    <tr>
        <td colspan="2">
            <b>Change Password</b>
        </td>
    </tr>
    <tr>
        <td>
            New Password
        </td>
        <td>
            :<asp:TextBox ID="txtNewPassword" TextMode="Password" 
            runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorNewPassword" 
                runat="server" ErrorMessage="New Password required"
                Text="*" ControlToValidate="txtNewPassword" ForeColor="Red">
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            Confirm New Password
        </td>
        <td>
            :<asp:TextBox ID="txtConfirmNewPassword" TextMode="Password" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorConfirmNewPassword" 
                runat="server" ErrorMessage="Confirm New Password required" Text="*" 
                ControlToValidate="txtConfirmNewPassword"
                ForeColor="Red" Display="Dynamic"></asp:RequiredFieldValidator>
            <asp:CompareValidator ID="CompareValidatorPassword" runat="server" 
                ErrorMessage="New Password and Confirm New Password must match"
                ControlToValidate="txtConfirmNewPassword" ForeColor="Red" 
                ControlToCompare="txtNewPassword"
                Display="Dynamic" Type="String" Operator="Equal" Text="*">
            </asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td>
                    
        </td>
        <td>
            &nbsp;<asp:Button ID="btnSave" runat="server" 
            Text="Save" onclick="btnSave_Click" Width="70px" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblMessage" runat="server">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:ValidationSummary ID="ValidationSummary1" 
            ForeColor="Red" runat="server" />
        </td>
    </tr>
</table>
</div>

ChangePassword.aspx.cs page code
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (!IsPasswordResetLinkValid())
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "Password Reset link has expired or is invalid";
        }
    }
}

protected void btnSave_Click(object sender, EventArgs e)
{
    if (ChangeUserPassword())
    {
        lblMessage.Text = "Password Changed Successfully!";
    }
    else
    {
        lblMessage.ForeColor = System.Drawing.Color.Red;
        lblMessage.Text = "Password Reset link has expired or is invalid";
    }
}

private bool ExecuteSP(string SPName, List<SqlParameter> SPParameters)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand(SPName, con);
        cmd.CommandType = CommandType.StoredProcedure;

        foreach (SqlParameter parameter in SPParameters)
        {
            cmd.Parameters.Add(parameter);
        }

        con.Open();
        return Convert.ToBoolean(cmd.ExecuteScalar());
    }
}

private bool IsPasswordResetLinkValid()
{
    List<SqlParameter> paramList = new List<SqlParameter>()
    {
        new SqlParameter()
        {
            ParameterName = "@GUID",
            Value = Request.QueryString["uid"]
        }
    };

    return ExecuteSP("spIsPasswordResetLinkValid", paramList);
}

private bool ChangeUserPassword()
{
    List<SqlParameter> paramList = new List<SqlParameter>()
    {
        new SqlParameter()
        {
            ParameterName = "@GUID",
            Value = Request.QueryString["uid"]
        },
        new SqlParameter()
        {
            ParameterName = "@Password",
            Value = FormsAuthentication.HashPasswordForStoringInConfigFile(txtNewPassword.Text, "SHA1")
        }
    };

    return ExecuteSP("spChangePassword", paramList);
}

In the next video, we will discuss about changing password by providing the current password.

6 comments:

  1. hi sir!

    i think, you forgot to write a code for change pasword in sqlProcedure,
    need to add just ;

    -- If UserId exists, Update with new password
    Update tblUsers set
    [Password] = @Password,
    *-----this------
    [IsLocked] = 0,
    [RetryAttempts] = 0
    *---------------
    where Id = @UserId


    ReplyDelete
  2. Hello sir ,,,,after i did all these stuffs im getting error says:
    HTTP Error 404.0 - Not Found
    The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

    ReplyDelete
  3. hello sir,
    when i reset my password i got a erroe of too many argument is passed in my storedprocedure which i define for changing password plz help

    ReplyDelete
  4. To Sukdev Mandal: add this line

    SqlCommand cmd = new SqlCommand(SPName, con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.parameters.clear();

    ReplyDelete
  5. i did all these but the final problem is that the new password is not saving in the database. The database is storing the GUID pin Number

    ReplyDelete
  6. Every time I run that first stored procedure to check if the link is valid I get this error "Msg 102, level 15, state 1, line 7 incorrect syntax near

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.