ASP.NET Snippet: Quick Password Reset

Here is a simple way, via code to reset a password when you are using the built-in ASP.NET authentication system. Useful if you either don't have a reset password form, or you just want to quickly change a password. Create a blank page, and place in the code behind Page_Load event.

C#

    protected void Page_Load(object sender, EventArgs e)
    {
        MembershipUser u = Membership.FindUsersByName("Username")["Username"];
        u.UnlockUser();
        u.ChangePassword(u.ResetPassword(), "newpassword");
    }

VB

    Public Sub Page_Load(sender As Object, e As EventArgs)
        Dim u As MembershipUser = Membership.FindUsersByName("Username")("Username")
        u.UnlockUser()
        u.ChangePassword(u.ResetPassword(), "newpassword")
    End Sub

Just delete the page when done.

Update (8 July 2009): If a question and answer is required when you create a user, you have to pass on the answer to u.ResetPassword, e.g. u.ChangePassword(u.ResetPassword("answer"), "newpassword"), otherwise ResetPassword won't work.

Comments

Luke said…
I get this when I try it:

Value cannot be null.
Parameter name: passwordAnswer

Thanks
Sam said…
This will be because you require a password question and answer when creating a user..
Anonymous said…
your membership provider in your web.config specifies requiresUniqueEmail="true"

Popular posts from this blog

Link: HTML Agility Pack (.NET)

Basic Excel Spreadsheet Generation (ASP/ASP.NET)

ASP.NET: Binding alphabet to dropdown list