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

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.

12 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
    Replies
    1. Yes when I login it throws error. I modified accordingly

      Delete
  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
  7. This code will fail in two cases :-

    1. if we copy the url(from email) and append few characters then also this url works.

    2. if we reduce the length of the original url at the end then it throws run time exception (cannot convert nvarchar to uniqueidentifier).

    ReplyDelete
  8. hello sir , i did as is in the video shown but i'm facing problem at the like " FormsAuthentication.HashPasswordForStoringInConfigFile(txtNewPassword.Text, "SHA1")"
    Even though i added the " System.web.security" i'm getting the warning like " FormAuthentication.... is absolete.

    and when i click the save button in forget password.aspx instead of given password the hash value is stored in database and this is creating problem when login is required..

    ReplyDelete
  9. Hello,

    I'm not getting the changepassword page after clicking the link. It's showing an error that the page was removed or renamed or others. But I have the page and the spelling is also correct.
    Can you help me out.

    ReplyDelete
  10. hello, i m using the same code but is show me an error
    Procedure or function 'SP_Is_Reset_password_is_Valid' expects parameter '@guid', which was not supplied.

    this is my code for check password reset link is valid

    private bool IsPasswordResetLinkValid()
    {
    List pramlist = new List()
    {
    new SqlParameter()
    {
    ParameterName="@guid",
    Value=Request.QueryString["uid"]
    }
    };

    return ExecuteSP("SP_Is_Reset_password_is_Valid", pramlist);
    }

    this is my executesp code

    private bool ExecuteSP(string spname,ListSPParameters)
    {
    using (con = new SqlConnection(cs))
    {
    if(con.State==ConnectionState.Open)
    {
    con.Close();
    }

    using (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());

    }
    }

    ReplyDelete
  11. I am getting below error.
    : 'Procedure or function 'spIsPasswordResetLinkValid' expects parameter '@GUID', which was not supplied.'

    ReplyDelete

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