How to force the user to change his password after first login?

Homam picture Homam · Mar 12, 2011 · Viewed 17.1k times · Source

I want to force the user to change his password after his first login. Now, where should I put the redirection code to ChangePassword page ?

  • If I put it in the Page_Load of Default page, user can move to any page because he is Authenticated.
  • If I put it in the Page_Load of Master page, the ChangePassword page uses the same master page, and it'll enter in an infinit loop of redirections.

    I though of ignoring the redirection if the Page is the ChagePassword page from the Master page, and I found this answer which says:

    This sounds like a bad idea to start with. The idea of the master is that it shouldn't care what page is there as this is all common code for each page.

Any suggestion!

Answer

Leniel Maccaferri picture Leniel Maccaferri · May 20, 2012

Here you are, a fully tested solution ;)

protected void LoginButton_Click(object sender, EventArgs e)
{
    /****note: UserName and Password are textbox fields****/

    if (Membership.ValidateUser(UserName.Text, Password.Text))
    {
        MembershipUser user = Membership.GetUser(UserName.Text);
        if (user == null)
        {
           FailureText.Text = "Invalid username. Please try again.";
           return;
        }
        if (user.IsLockedOut)
           user.UnlockUser();

        /* this is the interesting part for you */
        if (user.LastPasswordChangedDate == user.CreationDate) //if true, that means user never changed their password before
        {
            //TODO: add your change password logic here
        }
    }
}