Wednesday 17 December 2008

Changing password to a password of your choosing using Asp.Net Membership

You can use the Membership.Provider.ResetPassword method to change someone's password however you don't get to dictate the form of the password that is generated to any great extent (passwords will look like :{nV{l4ec2Z@#5 which isn't very helpful).

There is a method Membership.Provider.ChangePassword which sounds like it would do the job however it requires that you know the existing password. If you are using any form of encryption for the passwords in your Membership provider then you're not going to be able to get hold of that password!!

So your two options are:

1. Write a Custom Provider and override the GeneratePassword method
2. use this little trick:

string oldPassword = Membership.Provider.ResetPassword(username, null);

string newPassword = CreateRandomPassword(); // This is your custom GeneratePassword method

Membership.Provider.ChangePassword(username, oldPassword, newPassword);

So what you're doing here is first changing the password using the Membership provider's ResetPassword method, this will return you the password as a unencrypted string which is what you need! Then you can use the ChangePassword method and give it both the reset password one and a password that you want and the password will be changed successfully.

Easy when you know how!!

No comments: