Asp.Net and forcing password change after PasswordRecovery

Like many websites, we implemented a feature that will let our users self recover lost or forgottton passwords.  Asp.Net provides this right out of the box with the PasswordRecovery control.  It took us 90% of the way to where we want to be. It verifies the account exists, generates a random password and mails it to user.  The last step we wanted was to force the user to change their password after they’ve requested a new on from the PasswordRecovery control. Turns out, it wasn’t that bad.

We created a new profile property for our user to track if we were requiring a password change on the next login.

 <profile>
   <properties>
     <add name="RequirePasswordChange" type="System.Boolean" allowAnonymous="false"/>
   </properties>
 </profile>

We already had our ForgotPassword.aspx page with our PasswordRecovery control on it. We just needed to write up one more event.

<asp:PasswordRecovery ID="PasswordRecovery1" runat="server"
     OnSendingMail="SendingMail" >
 </asp:PasswordRecovery>

In the new event we’ll set that flag so we know the next time they successfully log in, we’ll make them change their password. I didn’t really see any other event that was more appropriate than SendingMail, but since we only send the e-mail when we pass all the challenges we’ve setup, it works well enough.

Also, since we’re not logged in, we have to ask for the profile by name, and then make the change.

protected void SendingMail(object sender, MailMessageEventArgs e)
{
    var p = Profile.GetProfile(PasswordRecovery1.UserName);
    p.RequirePasswordChange = true;
    p.Save();
}

The login page has some code added after we login.

<asp:Login ID="Login1" runat="server" OnLoggedIn="LoggedIn">
</asp:Login>

If we require the password change, then redirect to the new page.

protected void LoggedIn(object sender, EventArgs e)
{
    if (Profile.GetProfile(Login1.UserName).RequirePasswordChange)
        Response.Redirect("ChangePassword.aspx");
}

Lastly, ChangePassword.aspx resets the flag on successful login.

<asp:ChangePassword ID="ChangePassword1" runat="server"
    OnChangedPassword="ChangedPassword">
</asp:ChangePassword>
protected void ChangedPassword(object sender, EventArgs e)
{
    Profile.RequirePasswordChange = false;
    Profile.Save();
}

That’s it.

Leave a Reply